【问题标题】: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左连接在右侧有多行,如何将左侧的每一行合并为一行(我想要从右表连接的字段)?
【发布时间】:2013-07-16 02:15:37
【问题描述】:

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

这是我尝试过的(使用 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

但这只是返回一行包含每个产品的所有条形码concated,我怎样才能为每个产品获得一行带有产品条形码的行?

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

【问题讨论】:

    标签: mysql


    【解决方案1】:

    你需要一个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;
    

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

    【讨论】:

    • 效果很好!如果生成json格式的列表会更好
    • @eyal_katz 。 . .如果您有问题,您应该将其作为问题而不是评论提出。
    • 左表多行右表多行怎么样?
    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 2015-07-27
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多