Order of LIKE clause in query when wanting to use multiple terms

大城市里の小女人 提交于 2019-12-20 04:12:12

问题


I have the query

SELECT * FROM images WHERE tags LIKE '%example%hello%'

I would like the database to select rows which have 'example' and 'hello' in the 'tags' column in any order, as in:

A row with 'hello, test, example', also 'example, hello, test' or any other variation of this order. Is this possible, even without using LIKE? The rows must all contain everything specified with LIKE.

EDIT: Such as, when I provide 'example' and 'hello' in the query, rows returned must contain both 'example' and 'hello'.


回答1:


You could try a simple OR for a quick solution:

SELECT * FROM images WHERE tags LIKE '%example%' OR tags LIKE '%hello%'

EDIT

To address your edit, you can use AND instead:

SELECT * FROM images WHERE tags LIKE '%example%' AND tags LIKE '%hello%'



回答2:


You could use FIND_IN_SET:

SELECT tags FROM images WHERE FIND_IN_SET('hello', tags) AND FIND_IN_SET('example', tags)

However, this requires that tags not have spaces after the comma (you will have to do replace on tags or more boolean checks in that case). This might be faster than LIKE. I'm not sure.



来源:https://stackoverflow.com/questions/7910362/order-of-like-clause-in-query-when-wanting-to-use-multiple-terms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!