我需要解决以下问题:“列出需要至少一种产品但不要求牛奶的客户名称。我对此有一个粗略的开始,但是我不知道如何完成。这是到目前为止的内容
SELECT DISTINCT
Tb_Consumer.Con_ID, Tb_Consumer.Name
FROM
Tb_Consumer, Tb_Requests
WHERE
Tb_Consumer.Con_ID = Tb_Requests.Con_ID
AND Tb_Consumer.Con_ID NOT IN (SELECT Tb_Consumer.Con_ID)
我正在寻找的输出是这个。
Con_id Name
----------------
2 Hammer
4 Hoffer
答案 0 :(得分:1)
使用不存在,我假设您在表product_name
中有一个Tb_Requests
列
select distinct c.* from Tb_Consumer c join Tb_Requests t1 on c.Con_ID=t1.Con_ID
where not exists( select 1 from Tb_Requests t where c.Con_ID=t.Con_ID
and product_name='milk')
答案 1 :(得分:1)
可以使用EXISTS
而不是使用HAVING
。这将节省表tb_Requests
的2次扫描/查找。
SELECT C.Con_ID, C.[Name]
FROM Tb_Consumer C
JOIN Tb_Requests R ON C.Con_ID = R.Con_ID
GROUP BY C.Con_ID, C.[Name]
HAVING COUNT(R.Req_ID) > 0
AND COUNT(CASE R.Product_name WHEN 'Milk' THEN 1 END) = 0;