在MYSQL中使用GROUP_CONCAT的问题

时间:2013-06-06 06:41:23

标签: mysql group-concat

我有以下表格:

帖子:ID,标题,日期,内容

标记:id,name

posts_tags :post_id,tag_id

我想选择带有相关标签列表的标题;以下查询效果很好

SELECT p.title, GROUP_CONCAT( t.name ORDER BY t.name SEPARATOR ',' ) as tags_list
FROM posts AS p
JOIN posts_tags AS pt ON pt.post_id = p.id
JOIN tags AS t ON pt.tag_id = t.id
GROUP BY p.id

使用此查询我得到的内容看起来像这样

title             |  tags_list
==================|===============================
Old cinema        |  film,movies
cooking shows     |  cooking,food,kitchen,television
Epic War Films    |  history,movies,war
Art in France     |  art,france,history

当我只想发布带有某个标签的帖子(例如“电影”)时,我尝试添加一个where子句:

SELECT p.title, GROUP_CONCAT( t.name ORDER BY t.name SEPARATOR ',' ) as tags_list
FROM posts AS p
JOIN posts_tags AS pt ON pt.post_id = p.id
JOIN tags AS t ON pt.tag_id = t.id
WHERE t.name = 'movies'
GROUP BY p.id

我最终得到了这个

title            |  tags_list
=================|===============================
Old cinema       |  movies
Epic War Films   |  movies

我的所有帖子都标记为“电影”,但问题是“tags_list”列只显示每行中的“电影”,而不是包含与帖子关联的所有其他标签。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

条件需要放在GROUP_CONCAT的结果上,而不是每一行,所以@AshwinMukhija建议条件需要在HAVING子句中:

SELECT 
    p.title, 
    GROUP_CONCAT( t.name ORDER BY t.name SEPARATOR ',' ) as tags_list
FROM 
    posts AS p
JOIN posts_tags AS pt 
    ON pt.post_id = p.id
JOIN tags AS t 
    ON pt.tag_id = t.id
GROUP BY 
    p.id
HAVING
    FIND_IN_SET('movies',tags_list)
如果在逗号分隔列表FIND_IN_SET

中找到字符串影片,则

tags_list返回true

答案 1 :(得分:1)

您只需将标记上的条件从where子句转移到having

SELECT p.title, GROUP_CONCAT( t.name ORDER BY t.name SEPARATOR ',' ) as tags_list
FROM posts AS p
JOIN posts_tags AS pt ON pt.post_id = p.id
JOIN tags AS t ON pt.tag_id = t.id
GROUP BY p.id
HAVING t.name = 'movies'