Union Distinct行但按mysql中出现的次数排序

时间:2010-03-23 10:18:43

标签: sql mysql union

我有以下查询:

SELECT o.id,o.name FROM object o 
WHERE 
    (
        o.description LIKE '%Black%' OR
        o.name LIKE '%Black%'
    ) 
UNION ALL
SELECT o2.id,o2.name FROM object o2
WHERE 
    (
        o2.description LIKE '%iPhone%' OR
        o2.name LIKE '%iPhone%'
    ) 

其中包括以下内容:

id  name
2   New Black iPhone
1   New White iPhone
2   New Black iPhone

我想UNION DISTINCT,但我也希望结果按每个相同行的出现次数排序(主要:id)。

1 个答案:

答案 0 :(得分:5)

您可以在id和name列上对结果进行分组,并查看每个不同值的出现次数。 那么你可以通过首先出现的order by count(*) desc

出现的大多数事件来订购它们
select id, name, count(*) as occurences
from (
    SELECT o.id,o.name FROM object o 
    WHERE 
        (
            o.description LIKE '%Black%' OR
            o.name LIKE '%Black%'
        ) 
    UNION ALL
    SELECT o2.id,o2.name FROM object o2
    WHERE 
        (
            o2.description LIKE '%iPhone%' OR
            o2.name LIKE '%iPhone%'
        ) 
)
group by id, name
order by count(*) desc

这将返回

id  name              occurences
2   New Black iPhone  2
1   New White iPhone  1