加入条件

时间:2015-03-25 12:55:56

标签: sql

我有以下表格:

**payments**
ID  Sum
1   400
2   450
3   500

**orders**
ID  Payment
1   1       
2   3
3   2

**orders_info**
ID  ItemID  Qty Sum
1   1       1   400
2   12      2   225
3   8       1   500

其中:

payments.ID = orders.Payment
orders.ID = orders_info.ID

现在,如果我像下面这样加入,我会得到错误的结果:

select o.ID, sum(qty*sum)
from payments p
  inner join orders o on(p.ID = orders.Payment)
  inner join orders_info oi on(o.ID = oi.ID)
where oi.Qty < 2
group by o.ID

如果我这样加入,我会得到太多的行,因此sum()函数将返回太高的值。我需要来自orders_info的信息,而不必将其行与其他表相乘。我怎样才能做到这一点?

所以,基本上我希望从order_info获得所有支付以及它们的价值,除非数量小于2。

2 个答案:

答案 0 :(得分:2)

您只需将oi.Qty > 2移至联接的on-clause即可过滤该特定表格。

示例:

select o.ID,
       sum(oi.qty * oi.sum) -- Define if it should be p.sum or oi.sum!
  from payments     p
         inner join
       orders       o   on p.ID   = o.Payment
         inner join
       orders_info  oi  on o.ID   = oi.ID
                       and oi.Qty >= 2  -- This filters the specific table
group by o.ID

答案 1 :(得分:0)

奇怪的是你不会因为有两个列名而出现任何错误,&#34; sum&#34;是在付款和&#34; order_info&#34; ...

select o.ID, sum(p.sum) 
from payments p 
inner join orders o 
on(p.ID = orders.Payment) 
inner join orders_info oi 
on(o.ID = oi.ID) 
where oi.Qty < 2 
group by o.ID

select o.ID, sum(io.sum*qty) 
from payments p 
inner join orders o 
on(p.ID = orders.Payment) 
inner join orders_info oi 
on(o.ID = oi.ID) 
where oi.Qty < 2 
group by o.ID

任何一个都应该有效

如果你有以下它会太高:

select o.ID, sum(p.sum*qty) 
from payments p 
inner join orders o 
on(p.ID = orders.Payment) 
inner join orders_info oi 
on(o.ID = oi.ID) 
where oi.Qty < 2 
group by o.ID