MySQL:选择首先以SOMETHING开头然后包含SOMETHING的行

2w3rbyxf  于 2023-01-16  发布在  Mysql
关注(0)|答案(2)|浏览(142)

我想从标记表中选择标记名称包含某些内容的行。结果必须以智能方式排序:以某物开头的记录应该先走,然后应该走剩下的。
使用2个查询即可轻松实现:先按tag like 'SOMETHING%'选择,再按tag like '%SOMETHING%'选择,我想把这两个合并成一个查询,可以吗?一般来说,我想把WHERE子句中常用的一些公式出现在FIELDS节中,例如:

SELECT 
  *, 
  (`name` like 'SOMETHING' ? 1 : 0) as weight0,
  (`name` like 'SOMETHING%' ? 1 : 0) as weight1, 
  (match `name` against 'SOMETHING') as weight2, 
  length(name) as weight3 
FROM `tags` 
WHERE `name` like '%SOMETHING%'
ORDER BY weight0, weight1 desc, weight2 desc, weight3, name
LIMIT 0, 10

显然,上面的伪代码不起作用,但我希望它能显示目标:将WHERE条件移动到SELECT区域,分配数值,并按这些值排序。是否可以在MySQL中实现?

p4tfgftt

p4tfgftt1#

您可以使用条件语句,如“case when”

SELECT 
  *, 
  (case when `name` like 'SOMETHING' then 1 else 0 end) as weight0,
  (case when `name` like 'SOMETHING%' then 1 else 0 end) as weight1, 
  length(name) as weight3 
FROM `tags` 
WHERE `name` like '%SOMETHING%'
ORDER BY weight0, weight1 desc,  weight3, name
LIMIT 0, 10
juud5qan

juud5qan2#

对于true,MySql将布尔表达式计算为1;对于false,MySql将布尔表达式计算为0,它们可以在ORDER BY子句中使用:

SELECT *
FROM tags 
WHERE name LIKE '%SOMETHING%'
ORDER BY name = 'SOMETHING' DESC,
         name LIKE 'SOMETHING%' DESC,
         name LIKE '%SOMETHING%' DESC, -- this is not actually needed
         CHAR_LENGTH(name),
         name
LIMIT 0, 10;

相关问题