MySQL - 使用UNION ALL和GROUP BY进行搜索

时间:2010-10-10 20:13:21

标签: sql mysql database group-by union

SELECT p.id, p.title, p.uri, 'post' AS search_type
FROM `posts` AS p 
WHERE title LIKE "%logo%" 

UNION ALL 

SELECT p.id, p.title, p.uri, 'tag' AS search_type
FROM posts AS p 
INNER JOIN post_tags AS pt ON pt.post_id = p.id 
INNER JOIN tags AS t ON pt.tag_id = t.id 
WHERE t.title LIKE "%logo%"

UNION ALL

SELECT p.id, p.title, p.uri, 'category' AS search_type
FROM posts AS p 
INNER JOIN post_categories AS pc ON pc.post_id = p.id 
INNER JOIN categories AS c ON pc.category_id = c.id 
WHERE c.title LIKE "%logo%"

GROUP BY p.id
LIMIT 30

我正在尝试对帖子ID进行分组,因此我不会返回重复的搜索结果,但由于某些原因,即使我使用GROUP BY p.id也存在重复项。有人能告诉我我做错了吗?

2 个答案:

答案 0 :(得分:6)

GROUP BY只会对您的第三部分查询的结果进行分组。首先是GROUP,然后是UNION。

将整个查询括在子查询和GROUP上。

答案 1 :(得分:6)

以下是一个不适用于MySQL的示例:

SELECT Column1, SUM(Column2) AS Column2Total
FROM
(
    SELECT Column1, Column2 FROM Table1
    UNION ALL
    SELECT Column1, Column2 FROM Table2
) AS UnionTable
GROUP BY Column1