用于获取其列不应与其他表列匹配的表行的SQL查询

时间:2016-11-07 12:21:44

标签: sql

提前致谢,

实际上我有两张桌子推车和支票。购物车表包含以下行

id |username  |orderid  | exam_name | price
1  |  Rajesh  | ABC123  |   PMP     |  $60
2  |  Rajesh  | ABC123  |   CPM     |  $70
3  |  David   | ABC789  |  ITIL     |   $80

checks表包含以下行

id |username |order_id | exam      |  price
1    Rajesh  | ABC123  |   PMP     |  $60
2    Rajesh  | ABC123  |   CPM     |  $70

我需要一个carts表的行数据,其orderid列和exam_name列不应与check table order_id列和检查列匹配

如下所示:

id |username  |orderid  | exam_name | price
1  |  David   | ABC789  |  ITIL     |   $80

4 个答案:

答案 0 :(得分:2)

一种方法是not exists

select c.*
from carts c
where not exists (select 1
                  from checks ch
                  where ch.orderid = c.orderid and ch.exam_name = c.exam_name
                 );

类似的方法是left join

select c.*
from carts c left join
     checks ch
     on ch.orderid = c.orderid and ch.exam_name = c.exam_name
where ch.orderid is null;

在某些数据库中,您可以使用not in

select c.*
from carts c
where (c.orderid, c.exam_name) not in (select ch.orderid, ch.exam_name from checks ch);

答案 1 :(得分:2)

select c.*
from carts c
left join checks ch on c.id = ch.id
where ch.id is null;

希望这可以解决你的问题。

答案 2 :(得分:0)

SELECT *
from Carts 
where  exam_name  not in (select  exam       from checks) 
and id  not in (select id  from  checks)

答案 3 :(得分:0)

SELECT * FROM Carts 
WHERE NOT EXISTS (SELECT 1 FROM checks 
    WHERE checks.OrderId = Carts.OrderId 
    and Carts.exam_name = checks.exam_name)