【问题标题】:Selecting rows that don't exist when joining two tables连接两个表时选择不存在的行
【发布时间】:2015-12-05 01:58:36
【问题描述】:

我有两个可以使用一个字段连接的表:

Table_1: 

    emp_id  emp_name  department
    ------  --------  ----------
    1       Adam      Accounting
    2       Peter     Engineering
    3       Bruce     Engineering


Table_2: 

    emp_id  emp_salary
    ------  ----------
    1       1000 
    3       3500
    5       2000

我想选择表 2 中连接两个表时未出现的行(在本例中为 emp_id=5)。我一直在尝试以下语句,但我得到 0 行:

select * from table_2 
where not exists
(
select * from table_1, table_2
where table_1.emp_id = table_2.emp_id);

【问题讨论】:

  • 这两个语句之间没有关联;只要两个表中都有一个 ID,您的 EXISTS 子句将始终返回一些内容……换句话说,它始终为真,您需要将 table_2 链接到您的 EXISTS 子句。这应该可以帮助您看到您只想要table_2 中不存在于table_1 中的 ID 列表,这是一个更简单的命题。
  • 你应该改用内部连接
  • 这是一个内部连接@sra1。

标签: sql oracle join oracle11g


【解决方案1】:

如此简单,只需从子查询中删除 table_2:

select *
from table_2
where not exists (select 1
                  from table_1
                  where table_1.emp_id = table_2.emp_id);

【讨论】:

  • 非常简单的解决方案!谢谢!
【解决方案2】:

试试:

select * from table_2 
where
emp_id not in (select emp_id from table_1)

【讨论】:

  • NOT IN 如果 emp_id 可以为空,则有点危险。如果是这种情况,请将 where emp_id is not null 添加到子查询中。
【解决方案3】:

从 table_2 中选择 * 在哪里 emp_id 不在(从 table_1 中选择 emp_id)

如果 emp_id 在两个表中都是主要的,则可以使用此查询。

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2018-06-26
    • 2017-02-20
    • 2018-09-01
    • 2019-04-09
    • 2015-05-08
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    相关资源
    最近更新 更多