我查询一个表,其中每行有多个标记:
SELECT
user.*,
GROUP_CONCAT(tag.tag SEPARATOR ", ") as `tags`
FROM
user
LEFT JOIN
user_tag
ON
user_tag.user_id = user.id
LEFT JOIN
tag
ON
tag.id = user_tag.tag_id
GROUP BY
user.id
现在我希望能够按标签搜索用户。 所以在添加where之后,它看起来像这样:
SELECT
user.*,
GROUP_CONCAT(tag.tag SEPARATOR ", ") as `tags`
FROM
user
LEFT JOIN
user_tag
ON
user_tag.user_id = user.id
LEFT JOIN
tag
ON
tag.id = user_tag.tag_id
WHERE
tag.tag LIKE "%engineer%" OR
tag.tag LIKE "%programmer%"
GROUP BY
user.id
然而,这显然意味着如果找到结果,则标签表不再返回所有用户标签。因此,所选列tags
可能看起来像“php programmer”,即使用户有更多标签。
有没有办法搜索连接表而不使用子查询实际限制返回的结果?
答案 0 :(得分:1)
我的猜测是,如果你想避免子查询,你可以使用带有“标签”的HAVING子句,如下所示:
SELECT
user.*,
GROUP_CONCAT(tag.tag SEPARATOR ", ") as `tags`
FROM
user
LEFT JOIN
user_tag
ON
user_tag.user_id = user.id
LEFT JOIN
tag
ON
tag.id = user_tag.tag_id
GROUP BY
user.id
HAVING
tags LIKE "%engineer%" OR tags LIKE "%programmer%"
答案 1 :(得分:0)
您可以使用以下标签添加另一个JOIN:
SELECT
user.*,
GROUP_CONCAT(user_tags_to_return.tag SEPARATOR ", ") as `tags`
FROM
user
LEFT JOIN
user_tag user_tags_to_filter
ON
user_tags_to_filter.user_id = user.id
LEFT JOIN
tag tags_to_filter
ON
tags_to_filter.id = user_tags_to_filter.tag_id
WHERE
tags_to_filter.tag LIKE "%engineer%" OR
tags_to_filter.tag LIKE "%programmer%"
LEFT JOIN user_tag user_tags_to_return
ON user_tags_to_return.user_id = user.id
LEFT JOIN tag tags_to_return
ON tags_to_return.id = user_tags_to_return.tag_id
GROUP BY
user.id