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;
登录后复制