Mysql:按like排序?

2021-11-20 00:00:00 sql sql-like mysql sql-order-by

假设我们使用关键字执行搜索:keyword1、keyword2、keyword3

数据库中有name"列的记录:

<前>1:约翰·多伊2:塞缪尔·多伊3:约翰史密斯4:安娜史密斯

现在查询:

SELECT * FROM users WHERE (name LIKE "%John%" OR name LIKE "%Doe%")

它将选择记录:1,2,3(按此顺序)但我想按关键字订购例如 keyword1=John, keyword2=Doe所以应该按关键字列出:1,3,2(因为我想在搜索John"后搜索Doe")

我在考虑 SELECT DISTINCT FROM (...... UNION .....)但是以另一种方式对其进行排序会容易得多(真正的查询很长)

有什么技巧可以创建这样的订单吗?

解决方案

order by case当名字 LIKE "%John%" 然后 1当名称 LIKE "%Doe%" 然后 2其他 3结尾

assume that we are performing search using keywords: keyword1, keyword2, keyword3

there are records in database with column "name":

1: John Doe
2: Samuel Doe
3: John Smith
4: Anna Smith

now Query:

SELECT * FROM users WHERE (name LIKE "%John%" OR name LIKE "%Doe%")

it will select records: 1,2,3 (in this order) but i want to order it by keyword in example keyword1=John, keyword2=Doe so it should be listed by keywords: 1,3,2 (because i want to perform search for "Doe" after searching for "John")

I was thinking about SELECT DISTINCT FROM (...... UNION .....) but it will be much easier to order it somehow in another way (real query is really long)

are there any tricks to create such order?

解决方案

order by case 
    when name LIKE "%John%" then 1 
    when name LIKE "%Doe%"  then 2 
    else 3 
end

相关文章