如何对这个mysql查询排序

mspsb9vt  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(395)

我正在尝试在此查询中插入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'
fumotvh3

fumotvh31#

我想你想要:

SELECT CONCAT(
    GROUP_CONCAT(
        'SELECT ''', COLUMN_NAME,''' MyColumns, SUM(`', COLUMN_NAME,'`) Total FROM mydb.source_table' 
        SEPARATOR '\n UNION ALL \n'
    ),
    '\nORDER BY Total DESC'
)
INTO @sql
FROM  INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_SCHEMA = 'mydb' 
    AND TABLE_NAME   = 'source_table'
    AND COLUMN_NAME NOT IN ('ID', 'Name');

理由: ORDER BY 这个条款终究应该取消 UNION ALL 子查询-所以它需要在 GROUP_CONCAT() ,在外面 CONCAT() .
另外请注意,您不需要 CONCAT() 在内部 GROUP_CONCAT() :mysql在默认情况下已经做到了。

相关问题