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

时间:2016-08-25 03:04:31

标签: php mysql sql

我有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

这可能吗?

2 个答案:

答案 0 :(得分:2)

好的尝试一下。

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;

答案 1 :(得分:0)

请尝试以下sql查询。然后获得完整的行。

SHOW TABLES
相关问题