简体   繁体   English

使用MySQL的UNION中每个SELECT的ORDER BY不同

[英]Different ORDER BY for each SELECT in a UNION with MySQL

Using PHP and MySQL, is there a way to use a different ORDER BY for each of the SELECT statements in a UNION? 使用PHP和MySQL,有没有办法为UNION中的每个SELECT语句使用不同的ORDER BY?

SELECT * FROM the_table WHERE color = 'blue' ORDER BY price ASC LIMIT 5
UNION ALL
SELECT * FROM the_table WHERE color = 'red' ORDER BY RAND() LIMIT 10

The above statement does not work. 以上陈述不起作用。 It seems you can only do an ORDER BY on the final result set. 看来你只能对最终结果集进行ORDER BY。 Is there a way to do an ORDER BY on the first SELECT then a different ORDER BY on the second SELECT using UNION? 有没有办法在第一个SELECT上执行ORDER BY,然后使用UNION在第二个SELECT上执行不同的ORDER BY?

(SELECT * FROM the_table WHERE color = 'blue' ORDER BY price ASC LIMIT 5)
UNION ALL
(SELECT * FROM the_table WHERE color = 'red' ORDER BY RAND() LIMIT 10)

Please note that this does not work if you don't specify a LIMIT (though you can specify a very large dummy limit). 请注意,如果您未指定LIMIT,则不起作用(尽管您可以指定非常大的虚拟限制)。 See mysql documentation (13.2.7.3. UNION Syntax): 请参阅mysql文档(13.2.7.3.UNION语法):

"Use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows... "To cause rows in a UNION result to consist of the sets of rows retrieved by each SELECT one after the other, select an additional column in each SELECT to use as a sort column and add an ORDER BY following the last SELECT: “对单个SELECT语句使用ORDER BY并不意味着行在最终结果中出现的顺序,因为UNION默认生成一组无序行...”导致UNION结果中的行包含每个SELECT一个接一个地检索的行,在每个SELECT中选择一个附加列作为排序列,并在最后一个SELECT后面添加一个ORDER BY:

"(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1) UNION (SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col; To additionally maintain sort order within individual SELECT results, add a secondary column to the ORDER BY clause: “(SELECT 1 AS sort_col,col1a,col1b,... FROM t1)UNION(SELECT 2,col2a,col2b,... FROM t2)ORDER BY sort_col;要在单个SELECT结果中另外维护排序顺序,请添加辅助列到ORDER BY子句:

"(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1) UNION (SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col, col1a;" “(SELECT 1 AS sort_col,col1a,col1b,... FROM t1)UNION(SELECT 2,col2a,col2b,... FROM t2)ORDER BY sort_col,col1a;”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM