mysql查找字符串中的单词并按“最匹配”排序

时间:2019-01-09 18:55:57

标签: mysql

我有一张桌子,

--------------------------------------------------------------
|author_id   |  content                                      |
--------------------------------------------------------------
| 54         | I ate an apple and an orange for breakfast.   |
| 63         | Going to the store.                           |
| 12         | Should I wear the orange shirt?               |
--------------------------------------------------------------

我想找到带有apple , orange字样的行
运行查询
SELECT * FROM books WHERE content LIKE "%apple%" OR content LIKE "%orange%"
返回正确的值,但是因为真正的查询将包含两个以上的值,所以我想知道是否可以告诉sql根据大多数匹配对结果进行排序,例如,苹果和橙子都排在最前面的行

2 个答案:

答案 0 :(得分:1)

您可以使用MATCH(..) AGAINST (... IN BOOLEAN MODE)来计算相关性,ORDER BY 但是要使用它,您必须像评论中的tadman一样添加FULLTEXT索引。

SELECT 
 *
 , MATCH (Test.content) AGAINST ('apple orange' IN BOOLEAN MODE) AS relevance 
FROM 
 Test
WHERE 
 MATCH (Test.content) AGAINST ('apple orange' IN BOOLEAN MODE)
ORDER BY 
 MATCH (Test.content) AGAINST ('apple orange' IN BOOLEAN MODE) DESC

| author_id | content                                     | relevance            |
| --------- | ------------------------------------------- | -------------------- |
| 54        | I ate an apple and an orange for breakfast. | 0.25865283608436584  |
| 12        | Should I wear the orange shirt?             | 0.031008131802082062 |

请参阅demo

答案 1 :(得分:0)

如果您对content中相同单词出现的次数不感兴趣,可以尝试执行以下操作:

SELECT
  *,
  (content LIKE "%orange%") + (content LIKE "%apple%") AS matches
FROM
  test
WHERE
  content LIKE "%orange%"
OR
  content LIKE "%apple%"
ORDER BY
  matches DESC;

在线示例:

DB-Fiddle