[英]How do I combine select statements for all values in a many-to-many table
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"? 我如何将这段代码更改为单个SELECT,它可能还返回除“ id,title,keywords”之类的关键字(用空格分隔)之外的产品?
Such as (1, "hammer", "tool home hand"), (2, "blender", "kitchen home"), etc... 如(1,“锤子”,“工具回家的手”),(2,“搅拌器”,“厨房回家”)等...
You can use the GROUP_CONCAT but be aware of that it has the limit of character to group 您可以使用GROUP_CONCAT,但是要注意,它只能分组
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.