MySQL LIKE ...结果优先级排序

时间:2013-02-13 12:54:02

标签: mysql sql-order-by case sql-like

所以我决定用MySQL进行搜索...

SELECT * 
FROM items AS i 
INNER JOIN tags AS t ON i.id = t.item_id 
WHERE item LIKE ('%s%' OR '%s2%' ... OR '%sn%') 
  AND tag LIKE ('%s%' OR '%s2%' ... OR '%sn%');

它不是全文,item是VARCHAR(32),tag是VARCHAR(16)。

我有排序结果的问题...当涉及到一个搜索字符串时,我可以直接获得优先级,但是当我有更多时,它有点废话,我最终得到(搜索字符串的数量)+7个查询我觉得使用它真的很脏我觉得比实际使用它更糟糕...这就是它看起来像......

SELECT 
    t1.item_id, t1.item, t1.created, t1.owner, t1.type, t1.fld, t2.tag
FROM 
    items AS t1
INNER JOIN 
    tagged AS t2 ON t1.item_id = t2.item_id
WHERE 
    (item LIKE '%red%' OR '%apple%')
GROUP BY 
    item_id
ORDER BY 
    CASE 
       WHEN item = 'red'
         THEN 0 
       WHEN item = 'apple'
         THEN 1 
       WHEN (item LIKE 'red%' OR 'apple%')
         THEN 2 
       WHEN (item LIKE '%red%' AND '%apple%') 
        AND (tag LIKE '%red%' AND '%apple%')
        THEN 3 
      WHEN (item LIKE '%red%' AND '%apple%')
       AND (tag LIKE '%red%' OR '%apple%')
        THEN 4 
      WHEN (item LIKE '%red%' AND '%apple%')
        THEN 5 
      WHEN (item LIKE '%red%' OR '%apple%')
       AND (tag LIKE '%red%' OR '%apple%')
        THEN 6 
      WHEN (item LIKE '%red%' OR '%apple%')
        THEN 7 
      WHEN (tag LIKE '%red%' OR '%apple%')
        THEN 8 
      ELSE 9 
    END ASC , 
    created DESC 
LIMIT 0 , 30

是的,那很脏,怎么能把它砍下来?我实际上使用PHP脚本从搜索字符串生成该查询。那个查询只比它没有排序的查询慢一点,而且我们没有得到很高的负载,但对我来说感觉很脏。有更优雅的方式吗?

1 个答案:

答案 0 :(得分:0)

我更愿意推动案例...何时选择条款。我的查询看起来像这样:

SELECT field1, field2,
case 
 when field1 like 's1%' then 1
 when field1 like 's2%' then 2
end as ordering_field
from table_name
group by field1
order by ordering_field