WHERE(不是EXISTS(SELECT id ...有时它确实存在

时间:2014-02-23 14:36:36

标签: sql sql-server

我有2张桌子。我想从一个表中选择一个Id,根据日期在另一个表中不存在行...只是我似乎无法在第二个表中找到正确的行

表1

adId    info        tableX      tableY
1       blah, blah     Y          N
2       blah, blah     N          Y
3       blah, blah     N          N
4       blah, blah     N          Y
5       blah, blah     N          Y

表2

id      start_date  unitId      adId
1       2014-04-01    1          1
2       2014-03-02    2          1
3       2014-04-01    2          2
4       2014-03-01    0          4

Table2中unitID的关系来自两个表X和Y(我不确定它是否相关但我会在以下情况下对其进行描述)

TableX的

unitId    adid
1          1
2          1

TableY

unitId    adId
1           5
2           2
3           4

我想从表1中选择adId = 1,adId = 3,adId = 5,如表2所示,其中没有一个在3月份有日期(NB adId = 2和5在表2中根本没有出现)

这将找到adId = 2和5但不是1.

When I do SELECT TOP (100) PERCENT Table1.adId
FROM Table1
WHERE (NOT EXISTS
       (SELECT id, start_date
     FROM Table2
         WHERE (Table1.adId = adId) AND (Table2.start_date BETWEEN '2014-03-01'AND '2014-03-05)
    )
       )

如何添加子句以便在adId和UnitID上查找DISTINCT?

DISTINCT是解决这个问题的最好方法吗?还是有另一种方式?

3 个答案:

答案 0 :(得分:2)

  SELECT A.* 
  FROM Table1 A
  WHERE NOT EXISTS 
    ( SELECT 1 
        FROM Table2 B 
       WHERE B.start_date BETWEEN '2014-03-01'AND '2014-03-05' 
         AND B.adId = A.adId )

答案 1 :(得分:0)

您的方法似乎过于复杂。这个怎么样:

SELECT adId
FROM Table1
WHERE adId NOT IN
    (SELECT adId
     FROM Table2
     WHERE start_date BETWEEN '2014-03-01' AND '2014-03-05')

作为替代方案,如果你强烈反对WHERE条件中的子查询,你可以这样做:

SELECT Table1.adId
FROM Table1 LEFT JOIN (SELECT adId
     FROM Table2
     WHERE start_date BETWEEN '2014-03-01' AND '2014-03-05') T2
     ON Table1.adId=T2.adId
WHERE T2.adId=NULL

答案 2 :(得分:0)

您也可以使用MINUS集合运算符:

select adId
  from table1
 where start_date not between '2014-03-01' AND '2014-03-05'
minus
select adId
  from table1
 where start_date between '2014-03-01' AND '2014-03-05'