2

所以我决定在 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%');

它不是全文,项目是 VARCHAR(32),标签是 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 脚本。那个查询它只比没有排序的那个查询慢一点,而且我们没有得到高负载,但对我来说感觉很脏。有没有更优雅的方法来做到这一点?

4

1 回答 1

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
于 2013-03-13T17:23:05.070 回答