MySQL MySQL左连接右侧多行,如何将左侧的每一行合并为一行(我想要从右侧表中连接的字段)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17666940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:11:00  来源:igfitidea点击:

MySQL left join with multiple rows on right, how to combine to one row for each on left (with the field I want from the right table concated)?

mysql

提问by John V.

I have two MySQL tables, products, and barcodes. A product may have multiple barcodes, which is why I've separated it off into it's own table.

我有两个 MySQL 表、产品和条形码。一个产品可能有多个条形码,这就是为什么我把它分开到它自己的表中。

This is what I've tried (using CodeIgnighter's Active Record, but I've written out the query here, meaning if there is a typo, it mightnot be in my actual query):

这是我尝试过的(使用 CodeIgnighter 的 Active Record,但我已经在此处写出查询,这意味着如果有错字,它可能不在我的实际查询中):

SELECT
    products.id,
    products.snipe_price,
    group_concat(barcodes.barcode) as barcodes
FROM products
LEFT JOIN barcodes on barcodes.product_id = products.id

But this just returns one row with all of the barcodes from every product concated, how can I get one row for each product with the products barcodes?

但这只会返回一行,其中包含来自每个产品concated 的所有条形码,如何为每个带有产品条形码的产品获取一行?

I'd rather not have to split it up, but if there is no solution with jointhen please let me know.

我宁愿不必将其拆分,但如果没有解决方案,join请告诉我。

回答by Gordon Linoff

You need a group by:

你需要一个group by

SELECT products.id, products.snipe_price, group_concat(barcodes.barcode) as barcodes
FROM products LEFT JOIN
     barcodes
     on barcodes.product_id = products.id
group by products.id;

Without the group by, MySQL interprets the whole query as an aggregation query to summarize all the data (because of the presence of group_concat(), an aggregation function). Hence it returns only one row, summarized on all the data.

如果没有group by,MySQL 会将整个查询解释为聚合查询来汇总所有数据(因为存在group_concat(),聚合函数)。因此它只返回一行,汇总了所有数据。