2016-01-24 52 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告訴我回答這個