【问题标题】:JOIN 2 tables based by multiple ids mysqlJOIN 2个基于多个ID的表mysql
【发布时间】:2020-05-18 15:14:45
【问题描述】:

我有两张桌子,比如说订单

id | memberid | productsid |
----------------------------
 1 |   23     |   25,27

和产品

 id | product_name | price |
----------------------------
 25 |   product1   |   120
 27 |   product2   |   50

我想加入订单和产品表以从 productsid 获取每个 id 的产品名称和价格。 这就是我尝试为会员存储订单的方式。如果您有任何更好的解决方案,我正在等待知道。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    您可以借助 find_in_set() 功能加入表格,然后按每个订单分组,并使用 group_concat() 创建产品列表:

    select o.id, o.memberid,
      group_concat(p.product_name order by find_in_set(p.id, o.productsid)) products
    from orders o inner join products p
    on find_in_set(p.id, o.productsid)
    group by o.id, o.memberid
    

    请参阅demo
    结果:

    | id  | memberid | products          |
    | --- | -------- | ----------------- |
    | 1   | 23       | product1,product2 |
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多