MySQL LIKE 限制
基本上我的表中有一行,其值具有以下格式 - 1,2,3,4,10,11,21,34
等。
我正在使用 LIKE 检索值语句,但由于我将其与 %
一起使用,因此在搜索 1
时,它会返回 11、21、1 等。
我如何限制它,以返回基于 1 的值?
Basicly I have a row in my table, that has the following format for it's value - 1,2,3,4,10,11,21,34
etc..
I'm retrieving values with LIKE statement, but since I'm using it with %<value>%
, when searching for 1
it returns 11, 21, 1 and so on.
How can I limit it, to return values based on one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
find_in_set()< /code>
字符串函数:
请注意,这是一个纯粹的 MySQL 函数,如果不跳过巨大的障碍,在其他任何地方都无法使用。
Try the
find_in_set()
string function:Note that this is a purely MySQL function and isn't available anywhere else without jumping through huge hoops.
而不是
col LIKE '%%'
这样做或更好
但最好的解决方案是更改您的数据结构!使用
SET
类型、多个字段或连接表。Instead of
col LIKE '%<value>%'
door better yet
But the best solution is to change your data structure! Either use the
SET
type, or several fields, or a join table.如果您只想返回特定的匹配项,请使用 = 而不是 LIKE。 Like 意味着返回部分匹配,不像 = 只返回特定匹配。如果您只想匹配第一部分,请使用 %,但 11 仍会返回 111,但不会返回 211。一个常见的错误是对所有内容都使用 LIKE,或者删除 like 周围的 %%。另外,你的意思是你的MYSQL数据库中一行的VALUE是1,2,3,4,11,12等吗?如果是这样,您为什么要尝试根据其中的数字来搜索该值?我认为您会搜索整体的子集,例如 %3,4,11% 等...
If you want to return only a specific match, then use = instead of LIKE. Like is meant to return partial matches, unlike = which only returns specific matches. If you just want to match the first part, use %, but 11 would still return 111, but not 211. A common mistake is to use LIKE for everything, OR remove the %% around the like. Also, do you really mean that the VALUE for a row in your MYSQL database is 1,2,3,4,11,12 etc? And if so, why are you trying to search for that value based on a number that is in it? I would think you would be searching for a subset of the whole, such as %3,4,11% etc...
虽然我同意有关更改数据结构的其他答案,但您遇到的问题可以通过将每个值存储在两侧用分隔符封装的串行数据字段中来轻松解决。
我不推荐
,但如果您将数据从1,2,3,4,10,11,21,34
更改为,1, 2,3,4,10,11,21,34,
,您会注意到每个值的两侧都用逗号标记,因此您现在可以搜索%,, %
While I agree with the other answers regarding changing your data structure, the problem you are encountering can easily be fixed by storing every value in your serial data field encapsulated on both sides with a delimiter.
I don't recommend it
, but if you changed your data from1,2,3,4,10,11,21,34
to,1,2,3,4,10,11,21,34,
, you will note that each value is marked on both sides with a comma, so you can now search for%,<value>,%