Mysql:按like排序? [英] Mysql: Order by like?

查看:47
本文介绍了Mysql:按like排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们使用关键字执行搜索: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

这篇关于Mysql:按like排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆