简体   繁体   English

根据哪些行首先满足条件对sql查询中的行进行排序

[英]order rows in sql query based on which rows meet condition first

I would like to know if there is anyway in sql server to order rows based on which rows meet the conditions first , for example if i am writing a query like this 我想知道是否在sql server中根据首先满足条件的行对行进行排序,例如,如果我正在编写这样的查询

SELECT * FROM IMAGES 
WHERE NAME LIKE '%TEST%'
AND DESCRIPTION LIKE '%TEST%'

I want rows that match the name to appear before rows that match the description , usually sql server will arrange them by their ID , so...anyway to do this ?! 我希望与名称匹配的行出现在与描述匹配的行之前,通常sql server将按ID排列它们,所以...无论如何要这样做? (note : I dont want to use union statement as that's gonna exhaust the database ). (注意:我不想使用并集语句,因为这将耗尽数据库)。

You can use CASE statements in your ORDER BY clause to get what you are after. 您可以在ORDER BY子句中使用CASE语句来获取所需内容。

ORDER BY CASE(WHEN NAME LIKE '%TEST' THEN 1 ELSE 0 END) DESC

EDIT: 编辑:

Sample code as proof of concept in SQL Server: 示例代码作为SQL Server中的概念证明:

DECLARE @t table(id int)

INSERT INTO @t
VALUES
(1),
(2),
(3),
(4),
(5)

SELECT *
FROM @t
ORDER BY(CASE WHEN id > 3 THEN 1 ELSE 0 END) DESC

First, the UNION would not necessarily exhaust the database; 首先,UNION不一定会耗尽数据库。 as written, it might not make a difference at all, performance-wise, depending on how the query optimizer decided to handle it. 按照书面说明,就性能而言,这可能根本没有任何区别,具体取决于查询优化器决定如何处理它。

Second, as your where clause contains an "AND", all your results will match on both description and name, so I don't think that's what you want. 其次,由于您的where子句包含“ AND”,因此所有结果在描述和名称上都将匹配,因此我认为这不是您想要的。

Third, assuming you meant to have an "OR" in your query, you could try something like this: 第三,假设您要在查询中使用“ OR”,则可以尝试如下操作:

select
    *
from
    images i
where 
    i.name like '%TEST%'
    or i.description like '%TEST%'
order by
    case
        when i.name like '%TEST%' then 0
        else 1
    end asc;

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

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