MySQL - 如何按相关顺序排序? INNODB表

时间:2009-10-19 13:37:09

标签: mysql search sql-order-by innodb relevance

我在INNODB表中有大约20,000行称为'cards',所以FULLTEXT不是一个选项。

请考虑此表:

id     |     name     |     description
----------------------------------------------------------
1        John Smith       Just some dude
2        Ted Johnson      Another dude
3        Johnathan Todd   This guy too
4        Susan Smith      Her too
5        Sam John Bond    And him
6        John Smith       Same guy as num 1, another record
7        John Adams       Last guy, promise

因此,假设用户搜索“John”,我希望结果集的顺序为:

7        John Adams
6        John Smith
3        Johnathan Todd
5        Sam John Bond
2        Ted Johnson

请注意,我们只拉了一次'John Smith',我们最近参加了他的录取。由于我的数据,所有名字都是针对同一个人,不需要担心两个名叫John Smith的人。 想法?如果我能澄清任何事情,请告诉我。

1 个答案:

答案 0 :(得分:110)

版本1:

SELECT max(id) id, name
  FROM cards
 WHERE name like '%John%'
 GROUP BY name
 ORDER BY CASE WHEN name like 'John %' THEN 0
               WHEN name like 'John%' THEN 1
               WHEN name like '% John%' THEN 2
               ELSE 3
          END, name

第2版:

SELECT max(id) id, name
  FROM cards
 WHERE name like '%John%'
 GROUP BY name
 ORDER BY CASE WHEN name like 'John%' THEN 0
               WHEN name like '% %John% %' THEN 1
               WHEN name like '%John' THEN 2
               ELSE 3
          END, name