Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MYSQL中的where on sum(表1.列名称)<;表2.其他列_Mysql - Fatal编程技术网

MYSQL中的where on sum(表1.列名称)<;表2.其他列

MYSQL中的where on sum(表1.列名称)<;表2.其他列,mysql,Mysql,我有两个表产品和销售的产品 products -> id|name|quantity|price sold_products -> id|product_id|quantity 我需要的是计算已售出产品的数量总和,并检查总和是否大于产品表中的数量。像下面这样 select p.* from products as p and sold_products as sp where p.quantity > sum(sp.quantity) 提前感谢 您可以通过连接2个表并使用拥

我有两个表产品和销售的产品

products -> id|name|quantity|price
sold_products -> id|product_id|quantity
我需要的是计算已售出产品的数量总和,并检查总和是否大于产品表中的数量。像下面这样

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

提前感谢

您可以通过
连接
2个表并使用
拥有
分组方式来实现这一点:

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)
选择p.数量、总和(sp.数量)
从产品中提取p
内部连接以sp的形式销售产品
在p.id=sp.product\U id上
按p.id分组
p.数量<总和(sp.数量)

分组,有
就行了

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
它也在工作

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) 
从产品1中选择p.id、p.quantity、sum(sp.quantity)作为p
以p.id上的sp=p.id上的sp.product\U id组的身份加入已售出的产品
有总和(p.数量)<总和(sp.数量)
但是@Gouda Elalfy请回答这个问题,告诉我该如何分组