如何在 MySQL 中选择逗号分隔列表字段中的项目
我有一个名为 product
的表,在 category
字段中我插入了大约 5 到 6 个类别。
例如 2,3,4,5,12
就像这样。
但是当我使用这个查询时它不起作用:
SELECT * FROM product WHERE category in '3'
SELECT * FROM `product` WHERE `category` LIKE '%3%'
任何人都可以帮助修复它
I have a table named product
, where in the category
field I have inserted around 5 to 6 categories.
For example 2,3,4,5,12
just like that.
But when I use this query it doesn't work:
SELECT * FROM product WHERE category in '3'
SELECT * FROM `product` WHERE `category` LIKE '%3%'
can anyone help to fix it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅:http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set" rel="nofollow noreferrer"> mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
如果您没有 find_in_set ,此代码将是等效的:
否则您将得到 3 的误报
'13,23,40'
。警告
但请注意,将 CSV 列表放入字段中是非常不好的做法。
通过从字段中提取列表并将其以 1 对 N 关系放入另一个表中,您将获得更好的性能。
See: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
If you don't have find_in_set this code would be equivalent:
Otherwise you will get a false positive for 3 on
'13, 23, 40'
.Warning
Do note however that it's very bad practise to put a CSV list in a field.
You'll get much better performance by extracting the list out of the field and putting it in another table in a 1-to-N relation.
最好的做法是创建另一个表!
IE:
产品类别
int 产品编号
int 类别
与您想要实现它的方式,当类别“13”可用但您想要“3”时,您也会遇到问题
the best practice would be to create another table!
i.e.:
product_categories
int productid
int category
with the way you want to implement it, you would also have a problem when a category '13' is available, but you want to have '3'
我很抱歉这么说,但你应该重新设计你的数据库。
使用单个字段来存储多个连接总是很麻烦。
创建一个存储关系的附加表要容易得多。
I'm sorry to say it but you should redesign your database.
Using a single field to store multiple connections will always be a pain in the butt.
It is much easier to create an additional table that stores the relations.
IN 语句不起作用,因为您要求类别与“3”完全匹配,而实际上它是“2,3,4,5,12”。我认为它也应该放在圆括号中。
正如 user737767 所说,您确实应该规范化您的数据库,以便您拥有一个类别表、一个产品表另一个表格显示每个产品所属的类别。
您的 LIKE 语句也是一个坏主意,因为搜索“3”也会返回“23”等结果
The IN statement wont work because you are asking for the category to be an exact match of "3" when it is in fact "2,3,4,5,12". I think it should also be in round brackets.
As user737767 said you should really normalise your database so you have a table of categories, a table of products and another table to show which categories each product belongs to.
Your LIKE statement is also a bad idea because searching for "3" will also bring back results like "23"