我正在尝试在此查询中插入order by以对total列进行排序:
SELECT GROUP_CONCAT(CONCAT('SELECT ''', COLUMN_NAME,''' MyColumns, SUM(`', COLUMN_NAME,'`) Total FROM mydb.source_table') SEPARATOR '\n UNION ALL \n')
INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'mydb'
AND TABLE_NAME = 'source_table'
AND COLUMN_NAME NOT IN ('ID', 'Name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DROP PREPARE stmt;
结果如下:
+-----------+-----------+
| MyColumns | Total |
+-----------+-----------+
| ABC | 67.00 |
+-----------+-----------+
| DEF | 40.00 |
+-----------+-----------+
| GHI | 33.00 |
+-----------+-----------+
| JKL | 39.00 |
+-----------+-----------+
| MNO | 33.00 |
+-----------+-----------+
以下是我迄今为止尝试过但没有成功的方法:
1. mydb.source_table ORDER BY Total
2. SEPARATOR '\nUNION ALL\n' ORDER BY 'Total' ASC
3. SEPARATOR '\nUNION ALL\n ORDER BY Total' ASC
4. AND COLUMN_NAME NOT IN ('ID', 'Name') ORDER BY 'Total' ASC;
5. ORDER BY 'Total' ASC SEPARATOR '\nUNION ALL\n'
1条答案
按热度按时间fumotvh31#
我想你想要:
理由:
ORDER BY
这个条款终究应该取消UNION ALL
子查询-所以它需要在GROUP_CONCAT()
,在外面CONCAT()
.另外请注意,您不需要
CONCAT()
在内部GROUP_CONCAT()
:mysql在默认情况下已经做到了。