返回MySQL LIKE运算符命令的结果

时间:2014-01-23 12:44:08

标签: php mysql

我想按照我设置LIKE运算符的顺序得到结果。首先是包含标题覆盆子,然后是苹果和最后一颗梨的行。至于现在它只是按照我将它们插入表中的顺序返回行。

示例:

SELECT id FROM table WHERE 
title LIKE 'raspberry' OR 
title LIKE 'apple' OR 
title LIKE 'pear'

2 个答案:

答案 0 :(得分:3)

使用FIELD()

SELECT id 
FROM table 
WHERE title in ('raspberry','apple','pear')
ORDER BY field(title, 'raspberry','apple','pear')

答案 1 :(得分:0)

您也可以使用CASE

SELECT 
  id 
FROM
  TABLE 
WHERE title LIKE 'raspberry' 
  OR title LIKE 'apple' 
  OR title LIKE 'pear' 
ORDER BY 
  CASE
    WHEN title LIKE 'raspberry' 
    THEN 1 
    WHEN title LIKE 'apple' 
    THEN 2 
    WHEN title LIKE 'pear' 
    THEN 3 
    ELSE 4 
  END 

CASE Syntax