LIKE 子句将选择“2”但不是“12”来自一串字符
我有一个旧数据库,其中包含一个“User_Defined”字段,其中包含一个描述每个记录所属项目的字符串。项目 ID 是该字符串中以逗号分隔的数字。例如,记录可能包括:
2
12
22
2,12
2,8,10,12
2,12,20,120,220
当前查询类似于:
SELECT tbl_species.Species_ID,
tbl_species.Common_Name,
tbl_species.User_Defined
FROM tbl_species
WHERE User_Defined LIKE '%2';
在这种情况下,查询当然会返回字符串中任何位置包含“2”的所有记录。我在这里选择 2,但它可以是通过 PHP 变量传入的任何数字。
我的问题是如何设计查询,使其仅返回包含 2 但不包含 12、22、120 等的记录?
顺便说一句,我意识到解决这个问题的正确方法是创建一个查找表来处理这种关系,但如果我可以修补这个问题直到下一次重新设计,那就太好了!
谢谢!
I have a legacy database that includes a field 'User_Defined' containing a string describing which projects each record belongs to. The project IDs are comma-separated numbers in that string. For example, records might include:
2
12
22
2,12
2,8,10,12
2,12,20,120,220
The current query is something along the lines of:
SELECT tbl_species.Species_ID,
tbl_species.Common_Name,
tbl_species.User_Defined
FROM tbl_species
WHERE User_Defined LIKE '%2';
In this case, the query of course would return all the records that contain '2' anywhere in the string. I'm picking on 2 here, but it can be any number passed in via a PHP variable.
My question is how can I craft the query so that it returns only those records containing 2 but not 12, 22, 120, etc.?
BTW, I realize that the proper way to fix this would be to create a lookup table to handle this relation, but if I could patch this until the next redesign, it would be great!
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
FIND_IN_SET
:Try using
FIND_IN_SET
:在要搜索的列中添加前导和尾随逗号,然后搜索用逗号包围的值。
Add a leading and trailing comma to the column being searched, then search for your value surrounded by commas.
试试这个:
Try this: