简体   繁体   English

如何将多对多表中所有值的选择语句组合在一起

[英]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.

相关问题 如何通过Laravel中的多对多关系访问第三个表? - How do I access third table via Many-to-Many Relation in Laravel? 如何使用NotORM联接多对多表 - How do I JOIN many-to-many tables using NotORM 如何在Yii2中处理多对多关系 - How do I work with many-to-many relations in Yii2 如何使用 Laravel 5.2 获取所有类别(即多对多表上的所有记录)的所有产品的计数 - How to get count for all products for all categories (i.e all records on many-to-many table) with laravel 5.2 从多对多表中选择具有所有这些详细信息的项目……适当的解决方案? - Select item from many-to-many table that has all these details… proper solution? 从多对多表中选择所有数据的最有效方法是什么? - What is the most effective way to select all data from many-to-many table? SQL查询从3个表中选择多对多 - SQL query select from 3 table Many-to-Many 如何合并许多 select 语句 - How merge many select statements 如果我有2个表必须与标签表具有多对多关系,我是否需要2个中间表? - If I have 2 tables that must have many-to-many relationship to a tags table, do I need 2 intermediate tables? 如何 select 多对多关系表中的数据匹配所需值? - How to select the data from the many-to-many relationship table that matches the desired value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM