联合不同的行,但按 mysql 中出现的次数对它们进行排序

发布于 2024-08-25 19:15:06 字数 474 浏览 7 评论 0原文

我有以下查询:

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)的出现次数排序的结果。

I have the following query:

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%'
    ) 

Which procude the following:

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

I would like to UNION DISTINCT, but I would also like the result ordered by the number of occurrences of each identical row (primary: id).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

英雄似剑 2024-09-01 19:15:06

您可以根据 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

you can group your result on id and name columns and see how many occurences each distinct value has.
then you can order them by most occurences appearing first 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

this will return

id  name              occurences
2   New Black iPhone  2
1   New White iPhone  1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文