I have the following table, tags
(我有下表, 标签)
+---------+------------------------------+
| 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 |
+---------+------------------------------+
I would like to do a search for the keyword test
and order the results by relevance according to the position the keyword is placed in the string in field tag_name
.
(我想搜索关键字test
并根据关键字在tag_name
字段中字符串中的位置进行相关性排序。)
So the order of results would be 5, 1, 6, 2, 4, 3, 7
.
(这样结果的顺序将是5, 1, 6, 2, 4, 3, 7
。)
I've tried the code below, and it almost works, expect for the fact that LIKE 'test%' will return results that have the keyword test
in the middle of the string in the order of the unique ID not the position of the keyword in the string
(我已经尝试过下面的代码,并且几乎可以正常运行,因为事实上LIKE'test%'将以唯一ID的顺序而不是关键字的位置返回在字符串中间具有关键字test
结果。在字符串中)
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
The above code will return the following results:
(上面的代码将返回以下结果:)
+---------+------------------------------+
| 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 |
+---------+------------------------------+
The order becomes 5, 1, 6, 2, 4, 3, 7
instead of 5, 1, 6, 2, 3, 4, 7
(顺序变为5, 1, 6, 2, 4, 3, 7
而不是5, 1, 6, 2, 3, 4, 7
)
How do I return results based of the position of the keyword for LIKE 'test%', or is there a better way of achieving this?
(如何根据LIKE'test%'的关键字位置返回结果,还是有更好的方法来实现?)
Thank you!
(谢谢!)
ask by Busker McGreen Brian translate from so