2016-01-24 53 views
0

我有两个表的产品和sold_productsMYSQL凡总和(tabl1.column_name)<tabl2.other_column

products -> id|name|quantity|price 
sold_products -> id|product_id|quantity 

我需要的是从sold_products计算量的总和,并检查总和大于数量较大从产品表。像下面的东西;

select p.* from products as p and sold_products as sp where p.quantity > sum(sp.quantity) 

在此先感谢;

回答

1

您可以通过join 2表使这和使用havinggroup by

select p.quantity, sum(sp.quantity) 
from products as p 
inner join sold_products as sp 
on p.id = sp.product_id 
group by p.id 
having p.quantity < sum(sp.quantity) 
+0

感谢组如何发挥预期 –

0

Group BYHAVING将工作。

SELECT p.* 
FROM products AS p, sold_products AS sp 
WHERE p.id = sp.product_id 
GROUP BY p.id 
HAVING sum(sp.quantity) > p.quantity 
0

也工作

select p.id,p.quantity, sum(sp.quantity) from products1 as p inner 
join sold_products as sp on p.id = sp.product_id group by p.id 
having sum(p.quantity) < sum(sp.quantity) 

但@豪达Elalfy PLZ告诉我回答这个