2016-11-07 58 views
0

在此先感謝,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 

我需要的車表,它的OrderID列,EXAM_NAME列不應該配合檢查表的order_id列和考試的行數據列

事情是這樣的,如下:

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

'SELECT * FROM車CA LEFT OUTER JOIN檢查CH上ca.orderid <> ch.orderid和ca.exam_name <> ch.exam' – user5226582

回答

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); 
+0

最後的查詢工作正常。非常感謝您的幫助 –

+0

所有查詢工作正常。再次感謝 –

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

希望這應該解決你的問題。

+0

而不是使用id如果我使用orderid然後它工作正常。 –

0
SELECT * 
from Carts 
where exam_name not in (select exam  from checks) 
and id not in (select id from checks) 
0
SELECT * FROM Carts 
WHERE NOT EXISTS (SELECT 1 FROM checks 
    WHERE checks.OrderId = Carts.OrderId 
    and Carts.exam_name = checks.exam_name) 
相關問題