Mysql:根据'keyword'位置搜索数据库

Mysql: Search database based on 'keyword' position

我有以下 table、标签

+---------+------------------------------+
| tag_id  | tag_name                     |
+---------+------------------------------+
| 1       | test, subject                |
+----------------------------------------+
| 2       | subject, test, this          |
+----------------------------------------+
| 3       | how, is, subject, test, this |
+----------------------------------------+
| 4       | this, is, test, subject      |
+---------+------------------------------+
| 5       | test                         |
+---------+------------------------------+
| 6       | testing, microphone          |
+---------+------------------------------+
| 7       | microphone, this, is a, test |
+---------+------------------------------+

我想搜索关键字 test 并根据关键字在字段 [= 字符串中的位置按相关性对结果进行排序=37=]tag_name.

所以结果的顺序是 5, 1, 6, 2, 4, 3, 7

我试过下面的代码,它几乎可以工作,期待 LIKE 'test%' 将 return 结果具有关键字 test 在字符串的中间 唯一 ID 的顺序 而不是关键字的 位置 在字符串中

SELECT *
FROM tags
WHERE `tag_name` LIKE '%test%'
ORDER BY
  CASE
    WHEN `tag_name` LIKE 'test' THEN 1
    WHEN `tag_name` LIKE 'test%' THEN 2
    WHEN `tag_name` LIKE '%test' THEN 4
    ELSE 3
  END

以上代码将return得到以下结果:

+---------+------------------------------+
| tag_id  | tag_name                     |
+---------+------------------------------+
| 5       | test                         |
+---------+------------------------------+
| 1       | test, subject                |
+----------------------------------------+
| 6       | testing, microphone          |
+---------+------------------------------+
| 2       | subject, test, this          |
+----------------------------------------+
| 3       | how, is, subject, test, this |
+----------------------------------------+
| 4       | this, is, test, subject      |
+---------+------------------------------+
| 7       | microphone, this, is a, test |
+---------+------------------------------+

顺序变为5, 1, 6, 2, 4, 3, 7而不是5, 1, 6, 2, 3, 4, 7

如何根据 LIKE 'test%' 关键字的位置 return 结果,或者是否有更好的方法来实现这一点?

谢谢!

您也可以在 ORDER BY 上使用 LOCATE 使用以下解决方案:

SELECT *
FROM tags
WHERE `tag_name` LIKE '%test%'
ORDER BY CAST(`tag_name` LIKE 'test' AS UNSIGNED) DESC,
  CAST(`tag_name` LIKE '%test%' AS UNSIGNED) ASC,
  LOCATE('test', `tag_name`) ASC

您可以使用此查询调试上述查询。在那里你可以看到 ORDER BY 值:

SELECT *,
  CAST(`tag_name` LIKE 'test' AS UNSIGNED) AS KeywordOnly,
  CAST(`tag_name` LIKE '%test%' AS UNSIGNED) AS KeywordExists,
  LOCATE('test', `tag_name`) AS KeywordPosition
FROM tags
WHERE `tag_name` LIKE '%test%'
ORDER BY CAST(`tag_name` LIKE 'test' AS UNSIGNED) DESC,
  CAST(`tag_name` LIKE '%test%' AS UNSIGNED) ASC,
  LOCATE('test', `tag_name`) ASC

demo on dbfiddle.uk