简体   繁体   English

根据匹配的条件对SQL记录进行排序

[英]Sort SQL records based on matched conditions

I have this query: 我有这个问题:

SELECT * FROM table WHERE key LIKE '1,2,3,%' OR key LIKE '1,2,%' OR key LIKE '1,%'

Is it posible to sort records returned from this query based on which conditions was matched first. 是否可以根据首先匹配的条件对从此查询返回的记录进行排序。 I'd like to get all records that match key LIKE '1,2,3,%' first, then key LIKE '1,2,%' and the others after. 我想首先得到所有与key LIKE '1,2,3,%'匹配的记录,然后key LIKE '1,2,%'以及之后的其他记录。

For example, if I have these records: 例如,如果我有这些记录:

key: "1,2,3,4"
key: "1,2,5"
key: "1,4"
key: "1,2,5,6"
key: "1,3"
key: "1,2,3,4,7"
key: "1,2,4"

I would like them to be sorted like so: 我希望他们像这样分类:

key: "1,2,3,4"
key: "1,2,3,4,7"
key: "1,2,4"
key: "1,2,5"
key: "1,2,5,6"
key: "1,3"
key: "1,4"

Is it possible to do? 有可能吗?

Use MATCH ... AGAINST and order by rank. 使用MATCH ... AGAINST并按排名排序。 It exactly does what you want. 它完全符合你的要求。

.... ORDER BY CASE
WHEN key LIKE '1,2,3,%' THEN 1
WHEN key LIKE '1,2,%' THEN 2
ELSE 3
END

Does using "UNION" could do the job? 使用“UNION”可以完成这项工作吗?

SELECT * FROM table WHERE key LIKE '1,2,3,%' UNION SELECT * FROM table WHERE key LIKE '1,2,%' UNION SELECT * FROM table WHERE key LIKE key LIKE '1,%' SELECT * FROM table WHERE key LIKE'1,2,3,%'UNION SELECT * FROM table WHERE key LIKE'1,2,%'UNION SELECT * FROM table WHERE key LIKE key LIKE'1,%'

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

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