1

我有以下表格:

帖子:id、标题、日期、内容

标签: 身份证, 姓名

post_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”列仅在每一行中显示“电影”,而不包括与帖子关联的所有其他标签。

我怎样才能解决这个问题?

4

2 回答 2

2

条件需要放在GROUP_CONCATnot 每一行的结果上,所以@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如果在逗号分隔列表中找到字符串电影,则返回 truetags_list

于 2013-06-06T07:09:28.733 回答
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'
于 2013-06-06T06:45:09.143 回答