选择所有值不在另一个表中的行

时间:2013-07-18 21:27:12

标签: sql

这是我的桌子设计:

REQUEST(R_ID,attr1,attr2)
WIPS(R_ID,WIP,attr3,attr4)
SHIPPING(WIP,attr5,attr6)

如何限制查询以显示来自REQUEST的信息,但仅限于wipsREQUEST之间关联的所有WIPS不在SHIPPING的情况下1}}表。例如,SHIPPING表包含已发送的所有WIPS,我只想显示所有REQUEST未发送的WIPS行。任何帮助将不胜感激。

谢谢, -Steve

2 个答案:

答案 0 :(得分:1)

您可以使用not exists

执行此操作
select *
from request r
where not exists (select 1
                  from wips w join
                       shipping s
                       on w.wip = s.wip
                  where w.r_id = r.r_id
                 )

也就是说,如果请求中的wips的发货表中存在任何内容,则过滤掉该行。

答案 1 :(得分:0)

因为您正在查找wips associated between REQUEST and WIPS的行 排除与shipping的连接是不够的。我们需要与wip建立连接,以便开始:

SELECT *
FROM   request r
WHERE  EXISTS (
   SELECT 1
   FROM   wips w1
   LEFT   JOIN shipping s USING (wip)
   WHERE  w1.r_id = r.r_id
   AND    s.wip IS NULL
  )

如果您的RDBMS没有JOIN的USING子句,请改为使用:

   LEFT   JOIN shipping s ON s.wip = w1.wip

如果,您实际上是指,与request相关联的任何wips都无法连接到shipping

SELECT *
FROM   request r
WHERE NOT EXISTS (
   SELECT 1
   FROM   wips w1
   JOIN   shipping s USING (wip)
   WHERE  w1.r_id = r.r_id
  )
-- but has to have at least one wip connected?
AND    EXISTS (
   SELECT 1
   FROM   wips w1
   WHERE  w1.r_id = r.r_id
  )

-> SQLfiddle demonstrating important details.