[英]mysql: union re-use subquery
這里有張桌子:
ID City
1 Toronto
2 Toronto
3 Toronto
4 Toronto
5 NY
6 NY
如何獲得下表:
City Total
NULL 6
Toronto 4
NY 2
我打算使用union
:
(select city, count(*) as total from tbl group by city)
union
(select null, count(*) as total from tbl)
是否可以使用類似重用子查詢的方法:
(select city, count(*) as total from tbl group by city) tmp
union
(select null, count(*) as tmp from tbl)
或者 sql 已經優化
(select city, count(*) as total from tbl group by city)
union
(select null, count(*) as total from tbl)
?
至少在 MySQL 5.5 和更高版本中,您可以使用WITH ROLLUP
修飾符來獲取分組元素的總和,而無需額外查詢;
SELECT city, COUNT(*) AS total FROM tbl GROUP BY city WITH ROLLUP
city total
---------------
NY 2
Toronto 4
(null) 6
您不能重用查詢,但可以使用視圖重用代碼
create view my_view as
select city, count(*) as total
from tbl group by city
一旦創建了視圖,您就可以
select city, total
from my_view
union
select null, sum(total)
from my_view
1) 取別名只對加入成員和子查詢可見。 不適用於工會成員。
2)您編寫的查詢幾乎沒有意義:將 tmp 別名為表然后是標量?
要實現您想要實現的目標,您可以嘗試使用 CTE:
WITH tmp AS (SELECT city, COUNT(*) AS cnt GROUP BY city)
SELECT * FROM tmp UNION SELECT null, SUM(cnt) FROM tmp
我不知道性能差異會是什么。 如果您有關於city
的索引,我懷疑您會看到不同。
您在子查詢中使用WITH ROLLUP
,然后在外部查詢中安排排序以將匯總記錄放在首位:
SELECT *
FROM (SELECT city, COUNT(*) AS total FROM mytable GROUP BY city WITH ROLLUP) x
ORDER BY
CASE WHEN city IS NULL THEN 0 ELSE 1 END,
city
如果您打算按總計降序排列結果,那就更簡單了:
SELECT *
FROM (SELECT city, COUNT(*) AS total FROM mytable GROUP BY city WITH ROLLUP) x
ORDER BY total DESC
| city | total |
| ------- | ----- |
| | 6 |
| Toronto | 4 |
| NY | 2 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.