多个表,消除数据

时间:2014-09-16 20:38:39

标签: sql

假设有三个表T1T2T3

  • T1包含Ordernum列和bizdate
  • T2包含Ordernum列和Orderitem
  • T3包含Orderitem列和Catid

仅供参考:每个ordernum下有多个orderitems;每个ordertiem有多个catids。 我想消除任何itemnum有catid = 100的ordernums。

正如我所说,每个ordernum都有多个orderitem,所以我想消除所有orderitem,即使ordernum中只有一个orderitem有catid = 100。

换句话说,我想只打印ordernum,其中catid!= 100

4 个答案:

答案 0 :(得分:2)

您可以使用子查询来挑选具有该类别的订单,并用于过滤掉这些订单:

select
  OrderNum
from
  T1 as t
where
  not exists(
    select *
    from T1
    inner join T2 on T2.Ordernum = T1.Ordernum
    inner join T3 on T3.Orderitem = T2.Orderitem and T3.Catid = 100
    where T1.Ordernum = t.Ordernum
  )

答案 1 :(得分:0)

您可以使用EXISTS子句:

SELECT T1.OrderNum 
FROM T1
WHERE NOT EXISTS 
     (SELECT * FROM T2 INNER JOIN T3 ON T2.Orderitem = T3.Orderitem
      WHERE T1.OrderNum = T2.OrderNum AND T3.Catid != 100)

答案 2 :(得分:0)

您需要选择all,然后在where语句中排除它们。我认为这会奏效。

从T1 a1选择a1.OrderNum INNER JOIN T2 a2 ON a1.OrderNum = a2.OrderNum
INNER JOIN T3 a3 ON a2.Orderitem = a3.Orderitem
在哪里没有a1.OrderNum (从T2中选择ordernum,其中orderitem在中   (从T3中选择Orderitem,其中T2.OrderItem = OrderItem和Catid = 100))

或者使用subjoin可能更好:

中没有a1.OrderNum (从T2 sa2中选择sa2.ordernum,其中sa2.orderitem在中   (选择sa3.Orderitem
  在sa2.OrderItem = sa3.OrderItem和sa3.Catid = 100)上的INNER JOIN T3 sa3)

答案 3 :(得分:0)

在这里;

select * 
  from T1 
 where ordernum not in (select ordernum 
                          from t2,t3 
                         where t2.Orderitem=t3.Orderitem 
                           and t3.catid=100)