Home >Database >Mysql Tutorial >When using the ROLLUP modifier, is it possible to use the MySQL ORDER BY clause to sort the results?

When using the ROLLUP modifier, is it possible to use the MySQL ORDER BY clause to sort the results?

WBOY
WBOYforward
2023-08-26 19:01:18839browse

使用 ROLLUP 修饰符时,是否可以使用 MySQL ORDER BY 子句对结果进行排序?

Actually ROLLUP and ORDER BY are mutually exclusive in MySQL, so using them at the same time in a query is not a good practice. However, if we use ROLLUP in ORDER BY, the main disadvantage is that the summary rows will be sorted along with the rows they are calculated on. It's also worth noting that the sort order will determine the position of the summary rows.

The summary lines will be at the beginning in ascending order and at the end in descending order. Consider the following example to understand it more clearly -

mysql> Select * from (Select sr, SUM(PRICE) AS PRICE from ratelist GROUP BY sr WITH ROLLUP) AS Price ORDER BY Sr DESC;
+------+-------+
| sr   | PRICE |
+------+-------+
|    5 |   250 |
|    4 |   850 |
|    3 |  1005 |
|    2 |   630 |
|    1 |   502 |
| NULL |  3237 |
+------+-------+
6 rows in set (0.00 sec)

mysql> Select * from (Select sr, SUM(PRICE) AS PRICE from ratelist GROUP BY sr WITH ROLLUP) AS Price ORDER BY Sr ASC;
+------+-------+
| sr   | PRICE |
+------+-------+
| NULL |  3237 |
|    1 |   502 |
|    2 |   630 |
|    3 |  1005 |
|    4 |   850 |
|    5 |   250 |
+------+-------+
6 rows in set (0.01 sec)

The above is the detailed content of When using the ROLLUP modifier, is it possible to use the MySQL ORDER BY clause to sort the results?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete