Mysql LIKE按完全匹配排序

时间:2013-07-20 14:15:38

标签: php mysql

我有一个使用LIKE获取信息的查询

SELECT * FROM table WHERE column LIKE '%$search%'

现在如果我搜索"你好那里"它将返回类似

的内容
Oh hello there
Hello there
Hello there how are you

但是我想首先通过完全匹配对它进行排序,所以它应该像

Hello there
Hello there how are you
Oh hello there

顶部完全匹配,之后句子开头的完全匹配

3 个答案:

答案 0 :(得分:12)

试试这个

    SELECT * FROM table1 WHERE column LIKE '%$search%'
    order by case when column like '$search%'  then 1        //hello in begining
                  when column like '%$search%' then 2        //hello in middle
                  when column like '%$search'  then 3 end    //hello in end

watch demo here

答案 1 :(得分:7)

使用INSTR按照列中搜索字符串的位置对结果进行排序:;

SELECT * FROM table 
WHERE column LIKE '%$search%'
order by INSTR(column, '$search')

答案 2 :(得分:-2)

SELECT * FROM table WHERE column LIKE '%$search%' ORDER BY column