否定选择SQL查询

时间:2010-06-23 23:39:37

标签: sql sql-server tsql sql-server-2005

我的任务是从我们的sql数据库中返回一个否定选择。我会尽可能地定义标准。到目前为止,我还没有制作出有效的查询。

业务表

[公交车名称] [公交车ID]

活动表

[活动ID] [公交车ID]

活动扩展表

[分机ID] [活动ID] [巴士ID]

我需要在相关表格中没有该商家ID#记录的所有商家的商家名称。简单地说,所有企业都没有活动。业务ID可以存在于一个或两个关联表中。

在尝试使用联接进行查询而不是在语句中存在或不存在时,这会导致我几个小时的麻烦。没有成功。

有什么想法吗?

3 个答案:

答案 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 INNOT 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