简体   繁体   English

左联接不列出多行

[英]Left Join don't list multiple rows

I have problem listing multiple rows from two tables. 我在从两个表列出多个行时遇到问题。 I had make research but I didn't find solution that fit my needs. 我进行了研究,但没有找到适合自己需求的解决方案。 Multiple use of LEFT JOIN brings only 1 row this is problem similar to mine. 多次使用LEFT JOIN仅产生1行,这与我的问题类似。 How can an SQL query return data from multiple tables also did not help me :) SQL查询如何从多个表返回数据也没有帮助我:)

This is what I have and what I want. 这就是我拥有的,我想要的。 I have two table, for example; 例如,我有两个表。 Products and Amounts. 产品和金额。

product -> id - name
amount  -> id - pid - color - amount

product -> 1  - Book
           2  - Door
           3  - Table
amount  -> 1  - 1 - red - 5
           2  - 1 - blue- 10
           3  - 3 - green - 3

This is query I run with no problem: 这是我没有问题运行的查询:

SELECT product.id AS pid, 
product.name AS pname, 
sum(amount.amount) AS amnt 
FROM product 
LEFT JOIN amount ON product.id=amount.pid 
WHERE product.id='1'

And this is query I had problem with: 这是我有问题的查询:

SELECT product.id AS pid, 
product.name AS pname, 
sum(amount.amount) AS amnt 
FROM product LEFT JOIN amount ON product.id=amount.pid 
WHERE product.name LIKE '%o%'

The second query list only one row, but I expect this result: 第二个查询仅列出一行,但是我希望得到以下结果:

row1: 1 - Book - 15
row2: 2 - Door - null

Try using group by as : 尝试将group by用作:

SELECT product.id AS pid, product.name AS pname, sum(amount.amount) AS amnt FROM product LEFT JOIN amount ON product.id=amount.pid WHERE product.name LIKE '%o%' GROUP BY product.id

reason: Since sum() is an aggregate function it needs to know what elements to sum up for you. 原因:由于sum()是聚合函数,因此需要知道为您总结哪些元素。 otherwise it will sum all up into one value (which you got). 否则它将总计为一个值(您得到的值)。

See group by modifiers in the manual about details. 有关详细信息,请参见手册中的分组修饰符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM