天天看點

mysql case when 排序_Mysql Case when 查詢排序

這種算法也叫做分值查詢,将查詢的比對度指派一個數字.最後這個值進行排序

我的資料表裡面有兩個字段title, short_name

這裡有一個查詢排序需求:

1. 當查詢字元串完全等于short_name, 那麼此條記錄排最前面.

2 其次等于title

3 其次 %short_name.

4 其次 %title

5 其次 %short_name%

6 其次 %title%

以上面的6條需求對查詢結果進行排序

$string = "我的查詢字元串";

// 将查詢的值給一個叫orderme的值.然後使用這個值來進行排序. Then 後的結果為此字段的值

$result = db_query("

SELECT

*, CASE

WHEN short_name='{$string}' THEN 1

WHEN title='{$string}' THEN 2

WHEN short_name LIKE '{$string}%' THEN 3

WHEN title LIKE '{$string}%' THEN 4

WHEN short_name LIKE '%{$string}%' THEN 5

WHEN title LIKE '%{$string}%' THEN 6

END AS orderme

FROM mytable

WHERE short_name LIKE '%{$string}%'

OR

title LIKE '%{$string}%'

ORDER BY orderme ASC LIMIT 20");