我想查询购买某些商品的客人的数据库。我想看看客户购买的商品是什么'A'而不是商品'B'。
我试过了:
SELECT customerName
FROM Customers
WHERE NOT item = 'A' AND item = 'B';
但是我回来了购买这两件商品的顾客。我想从该查询中排除这些客户。
我正在使用SQLite
答案 0 :(得分:1)
有多种方法可以做到这一点。我喜欢使用group by
和having
,因为它在很多条件下都非常灵活:
SELECT customerName
FROM Customers
GROUP BY customerName
HAVING SUM(CASE WHEN item = 'A' THEN 1 ELSE 0 END) > 0 AND
SUM(CASE WHEN item = 'B' THEN 1 ELSE 0 END) = 0;
答案 1 :(得分:0)
您还可以使用MINUS运算符,该运算符返回第一个SELECT语句中未被第二个SELECT语句返回的所有行。如:
(SELECT customerName FROM Customers WHERE item='A')
MINUS
(SELECT customerName FROM Customers WHERE item='B');
答案 2 :(得分:0)
我会将EXISTS
用于NOT EXISTS
:
select c.*
from Customers c
where exists (select 1
from Customers c1
where c1.customerName = c.customerName and c1.item = 'A'
) and not exists
(select 1
from Customers c2
where c2.customerName = c.customerName and c2.item = 'B'
);