dongziduo9762 2014-02-17 20:26
浏览 34
已采纳

如何在多对多表中为所有值组合select语句

I'm working on an existing product database trying to clean things up. I have the following tables:

Tables

<products> id, title
<keywords> id, title
<product_has_keyword> product_id, keyword_id

When I want to generate a list of products I use the code:

SELECT * FROM products;

And then for each product:

SELECT k.title FROM keywords k, product_has_keyword phk WHERE k.id = phk.keyword_id AND phk.id = ?

How would I change this code into a single SELECT that perhaps returns products in addition to the keywords (separated by spaces) like "id, title, keywords"?

Such as (1, "hammer", "tool home hand"), (2, "blender", "kitchen home"), etc...

  • 写回答

1条回答 默认 最新

  • dongsetan3216 2014-02-17 20:30
    关注

    You can use the GROUP_CONCAT but be aware of that it has the limit of character to group

    SELECT p.id, p.title ,GROUP_CONCAT(k.title SEPARATOR ' ') `keywords`
    FROM 
    products p
    LEFT JOIN product_has_keyword phk ON(p.id = phk.product_id)
    LEFT JOIN keywords k ON (k.id = phk.keyword_id )
    WHERE  phk.id = ?
    GROUP BY p.id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作