Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.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 使用联接查找数量总和的Sql查询_Mysql_Sql_Join_Select_Inner Join - Fatal编程技术网

Mysql 使用联接查找数量总和的Sql查询

Mysql 使用联接查找数量总和的Sql查询,mysql,sql,join,select,inner-join,Mysql,Sql,Join,Select,Inner Join,这里,在billtran表中,productid=1重复两次 我想分别查找每个productid的sumbilltran.quantity 选择查询1: select name,billtran.quantity from product inner join billtran on product.id=billtran.productid where product.id in(select id from product) 根据评论: select name, SUM(billtran

这里,在billtran表中,productid=1重复两次

我想分别查找每个productid的sumbilltran.quantity

选择查询1:

 select name,billtran.quantity from product inner join billtran on product.id=billtran.productid where product.id in(select id from product)
根据评论:

select name, SUM(billtran.quantity) from product inner join billtran on product.id=billtran.productid where product.id in(select id from product)
GROUP BY NAME
我的帽子

注意:where product.id inselect id from product是一个完全无用的where子句,应该删除。查询不必有where子句,也不需要一个表示表id应该在该表的所有id中始终为true的子句

因此,我会将这一条写为:

SELECT
  p.name,
  SUM(b.quantity) as sumof_quantity
FROM 
  product p
  INNER JOIN billtran b ON p.id=b.productid 
GROUP BY 
  p.name

首先,您必须根据产品id获得数量的总和

结果将是:

name    quantity
abc      6
xyz      1
pqt      3
您也可以通过对product.name进行分组来获得相同的结果:


非常简单的查询。请检查以下内容:
选择product.name,sumbilltran.quantity from product internal join billtran on product.id=billtran.productid group by billtran.productid

然后,按产品名称分组并求和数量。请不要使用图像。将表格和代码粘贴为文本。请求应无需任何图片即可理解。您也可以使用图像,但它们只能增强信息,例如添加ERM图。有些人甚至看不到你的图像,因为他们被阻止了。在“从产品中选择id”中的product.id?这是怎么回事?确保产品表中存在从产品表读取的ID???这毫无意义。你的顶级查询之所以有效,是因为它会自动根据每个id随机选取一个产品名称;其他企业级的dbs和mysql在“完全”模式下不接受
name    quantity
abc      6
xyz      1
pqt      3
SELECT  product.name, SUM(billtran.quantity) AS value_sum 
FROM billtran inner join product on product.id=billtran.product_id where product.id in(select id from product) 
GROUP BY  product.name;