繁体   English   中英

SQL查询从3个表中选择多对多

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM