我在名为“ cards”的INNODB表中大约有20,000行,因此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的家伙。有想法吗?让我知道是否可以澄清任何事情。
版本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