简体   繁体   English

订单条件

[英]ORDER BY condition

I would like to retrieve an ordered query result, but I need to have some specific row(s) to be in front of the list. 我想检索一个有序的查询结果,但是我需要在列表的前面有一些特定的行。 Something like here on Stack Overflow, in the list of answers the right answer is always the first one. 类似于“堆栈溢出”中的内容,在答案列表中,正确的答案始终是第一个答案。

Assumed I need to have the rows with IDs 1,2,3 to be the head, the rest sorted by a date field, is it possible to do something like: 假设我需要将ID为1,2,3的行作为标题,其余按日期字段排序,是否可以执行以下操作:

SELECT * FROM foo ORDER BY id IN (1,2,3), created_date

If not what is more efficient? 如果没有,哪个更有效率? There will be many rows! 将有很多行!

SELECT *, 0 AS head FROM foo WHERE id IN (1,2,3) 
UNION
SELECT *, 1 AS head FROM foo WHERE id NOT IN (1,2,3)
ORDER BY head, created_date

or 要么

SELECT *, IF(id IN (1,2,3), 0, 1) AS head
ORDER BY head, created_date

(I use MySQL now, but I'm interested in any other SQL solution.) (我现在使用MySQL,但是我对其他任何SQL解决方案都感兴趣。)

UNION means UNION DISTINCT and this is relatively slow as it will check for duplicates even though there will not be any. UNION表示UNION DISTINCT,这相对较慢,因为即使没有重复,它也会检查重复项。 You want UNION ALL: 您想要UNION ALL:

SELECT *, 0 AS head FROM foo WHERE id IN (1,2,3) 
UNION ALL
SELECT *, 1 AS head FROM foo WHERE id NOT IN (1,2,3)
ORDER BY head, created_date

I would imagine that after this change there is not much difference in performance between the three queries. 我可以想象,在进行此更改之后,这三个查询之间的性能没有太大差异。 The best way to be sure is to measure it. 最好的确定方法是测量它。

Your first example looks almost there to me. 您的第一个例子对我来说差不多。

SELECT * FROM foo ORDER BY id IN (1,2,3) DESC, created_date ASC

Added DESC because id IN (1,2,3) returns 1 if true or 0 if false. 添加了DESC因为id IN (1,2,3)如果为true,则返回1 0如果为false,则返回0 1 > 0 , so ordering them in descending order gets the desired result. 1 > 0 ,因此按降序对其进行排序可获得所需的结果。

Added ASC because I like to be explicit. 添加了ASC因为我喜欢明确。

Based on your later examples, I think what you're missing is that, though it contains spaces, field IN (list) is a single operator that returns 0 or 1 . 根据后面的示例,我认为您缺少的是,尽管field IN (list)包含空格,但它是返回01的单个运算符。 IF(id IN (1,2,3), 0, 1) is inherently redundant. IF(id IN (1,2,3), 0, 1)本质上是冗余的。

As such, you shouldn't need to use a UNION or sort manually, since MySQL makes this simpler than you even realize :) 因此,您不需要使用UNION 手动排序,因为MySQL使此操作比您甚至意识到的还要简单:)

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

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