[英]SQL query select from 3 table Many-to-Many
我有3张桌子:
桌post
:
post_id | title --------------------------------- 1 | post number 1 2 | post number 2 3 | post number 3
表categories
:
category_id | cate_name -------------------------------- 1 | video 2 | review 3 | gameplay
表post_categories
:
post_id | category_id --------------------------------- 1 | 1 2 | 2 3 | 3 2 | 1 3 | 2 1 | 3
如何选择post's title
和category's name
? 结果应如下所示:
title | cate_name ----------------------------------------- post number 1 | video, gameplay post number 2 | video, review post number 3 | review, gameplay
这可能吗?
好的,尝试一下。
SELECT DISTINCT
post.title as title,
GROUP_CONCAT(categories.cate_name) as cate_name
FROM post
LEFT JOIN post_categories
ON post_categories.post_id = post.post_id
LEFT JOIN categories
ON post_categories.category_id = categories.category_id
GROUP BY post.post_id;
请尝试以下sql查询。然后您将获得完整的行。
select post.title,GROUP_CONCAT(categories.cate_name SEPARATOR ', ') from post_categories join post ON post.post_id=post_categories.post_id join categories ON categories.category_id=post_categories.category_id group by post.title
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.