我的任务是从我们的sql数据库中返回一个否定选择。我会尽可能地定义标准。到目前为止,我还没有制作出有效的查询。
[公交车名称] [公交车ID]
[活动ID] [公交车ID]
[分机ID] [活动ID] [巴士ID]
我需要在相关表格中没有该商家ID#记录的所有商家的商家名称。简单地说,所有企业都没有活动。业务ID可以存在于一个或两个关联表中。
在尝试使用联接进行查询而不是在语句中存在或不存在时,这会导致我几个小时的麻烦。没有成功。
有什么想法吗?
答案 0 :(得分:23)
NOT IN
SELECT b.*
FROM BUSINESS b
WHERE b.business_id NOT IN (SELECT a.business_id
FROM ACTIVITY a)
AND b.business_id NOT IN (SELECT ae.business_id
FROM ACTIVITY_EXTENSION ae)
NOT EXISTS
SELECT b.*
FROM BUSINESS b
WHERE NOT EXISTS (SELECT NULL
FROM ACTIVITY a
WHERE a.business_id = b.business_id)
AND NOT EXISTS (SELECT NULL
FROM ACTIVITY_EXTENSION ae
WHERE ae.business_id = b.business_id)
LEFT JOIN/IS NULL
SELECT b.*
FROM BUSINESS b
LEFT JOIN ACTIVITY a ON a.business_id = b.business_id
LEFT JOIN ACTIVITY_EXTENSION ae ON ae.business_id = b.business_id
WHERE a.business_id IS NULL
AND ae.business_id IS NULL
因为关系是外键(business_id),所以假设它们都不为null是安全的。在这种情况下,NOT IN
和NOT EXISTS
是在SQL Server中查找缺失值的最佳方法。 LEFT JOIN / IS NULL效率较低 - you can read more about it in this article。
答案 1 :(得分:5)
SELECT * FROM businesses WHERE business.id NOT IN (SELECT DISTINCT business_id FROM activities)
答案 2 :(得分:1)
我会使用左连接和联合的组合,例如:
select * from Business b left join (select id, bid from Activity union select id, bid from ActivityExtension) a on b.id=a.bid where a.bid=null