登录
首页 >  数据库 >  MySQL

如何将多条查询同一表不同分组结果的SQL语句合并成一条语句执行?

时间:2024-12-01 16:49:05 194浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《如何将多条查询同一表不同分组结果的SQL语句合并成一条语句执行?》,聊聊,我们一起来看看吧!

如何将多条查询同一表不同分组结果的SQL语句合并成一条语句执行?

mysql语句合并优化

问题:给定多条查询同一表不同分组结果的sql语句,能否将其合并成一条sql语句执行?

select *, count(*) as count from t_search where mark = 'a' group by title order by count desc limit 0, 20

select *, count(*) as count from t_search where mark = 'b' group by title order by count desc limit 0, 20

select *, count(*) as count from t_search where mark = 'c' group by title order by count desc limit 0, 20

...

总共有24条sql语句,每个查询的mark字段从a到z,每条语句查询20条结果。

解答:

方法1:mysql 8.0+

使用with子句和窗口函数:

with ranked_data as (
    select *,
           count(*) over (partition by title, mark) as count,
           row_number() over (partition by mark order by count(*) desc) as row_num
    from t_search
    where mark between 'a' and 'z'
    group by title, mark
)
select *
from ranked_data
where row_num <= 20
order by mark, count desc;

方法2:mysql 8.0以下

使用变量和子查询:

SELECT *
FROM (
    SELECT *,
           @rank := IF(@prev_mark = mark, @rank + 1, 1) AS rank,
           @prev_mark := mark,
           COUNT(*) AS count
    FROM t_search
    JOIN (SELECT @rank := 0, @prev_mark := '') AS vars
    WHERE mark BETWEEN 'a' AND 'z'
    GROUP BY title, mark
    ORDER BY mark, count DESC
) AS ranked_data
WHERE rank <= 20
ORDER BY mark, count DESC;

今天关于《如何将多条查询同一表不同分组结果的SQL语句合并成一条语句执行?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>