我有两个相同的表:money_stat_buy和money_stat_buy_tmp(为简单起见,我删除了一些列):
id int(11) AI PK
artikul_id int(11)
n int(11)
我想从n
两个表中获取列artikul_id
组的总和。我使用了带有UNION语句的查询。
我得到了正确的结果,但按总和排序不起作用。
SELECT artikul_id, SUM(cnt)
FROM
( SELECT artikul_id, SUM(n) as cnt
FROM mhouse_diff.money_stat_buy table1
GROUP BY artikul_id
UNION ALL
SELECT artikul_id, SUM(n) as cnt
FROM mhouse_diff.money_stat_buy_tmp table2
GROUP BY artikul_id
)
table_derived
GROUP BY artikul_id
ORDER BY SUM(cnt) DESC;
+------------+----------+
| artikul_id | SUM(cnt) |
+------------+----------+
| 6793 | 6 |
| 16516 | 15 |
| 12212 | 10 |
| 7805 | 3 |
| 8750 | 1 |
...
我设法通过从内部查询中删除GROUP BY
语句并选择n
而不是SUM(n)
来解决此问题:
SELECT artikul_id, SUM(cnt)
FROM
( SELECT artikul_id, n as cnt
FROM mhouse_diff.money_stat_buy table1
UNION ALL
SELECT artikul_id, n as cnt
FROM mhouse_diff.money_stat_buy_tmp table2
)
table_derived
GROUP BY artikul_id
ORDER BY SUM(cnt) DESC;
+------------+----------+
| artikul_id | SUM(cnt) |
+------------+----------+
| 5654 | 2062 |
| 17522 | 2006 |
| 17979 | 190 |
| 8052 | 90 |
...
但我想知道为什么第一个查询不对结果进行排序。有什么错误???
此外 - 第一个查询在我的本地计算机上运行良好(就像它应该的那样排序)但是在生产环境中不起作用(不排序)。
本地mysql版本: mysql Ver 14.14 Distrib 5.5.46,debian-linux-gnu(x86_64)使用readline 6.3
生产环境mysql版本: mysql Ver 14.14使用EditLine包装器为debian-linux-gnu(x86_64)分发5.5.40-36.1
P.S。此处甚至不需要UNION
语句 - 以下查询也不排序:
SELECT artikul_id, SUM(cnt)
FROM
( SELECT artikul_id, SUM(n) as cnt
FROM mhouse_diff.money_stat_buy table1
GROUP BY artikul_id
)
table_derived
GROUP BY artikul_id
ORDER BY SUM(cnt) DESC;