字符串中字符串查询?
我有这个数据库,我在其中存储了一些标签。 我像这样存储标签:
"humor,funny,animal"
现在我需要一个 mysql 查询,当我搜索“幽默”、“有趣”或“动物”时,它会选择这一行。到目前为止我所拥有的:
SELECT id FROM database WHERE tags REGEXP 'humor' LIMIT 1
不幸的是,它不起作用。你们中有人可以帮我吗?
编辑:感谢您的所有回复!我现在需要先研究这个!但问题解决了:)
I have this database where I have stored some tags in it.
I stored the tags like this:
"humor,funny,animal"
Now I need a mysql query that selects this line when I search for "humor", "funny" or "animal". What I have until now:
SELECT id FROM database WHERE tags REGEXP 'humor' LIMIT 1
Unfortunately, it does not work. Could someone of you please help me out?
Edit: Thanks for all the responses! I will now need to study this first! But problem solved :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
短期
因为标签存储为非规范化数据,所以使用 FIND_IN_SET 函数:
长期解决方案
设置表以正确处理多对多关系:
TAGS
ITEMS
ITEM_TAGS
将 ITEM_TAGS 中的两列作为主键意味着您不必担心重复。是的,这意味着使用 InnoDB 引擎...
然后,您可以使用:
Short Term
Because the tags are stored as denormalized data, use the FIND_IN_SET function:
Long Term Solution
Setup the tables to properly handle a many-to-many relationship:
TAGS
ITEMS
ITEM_TAGS
Making the two columns in ITEM_TAGS the primary key means you don't have to worry about duplicates. And yes, this means using the InnoDB engine...
Then, you can use:
您可以使用
LIKE
它将搜索“humor”为子字符串的任何条目。请注意,这还将返回标记为“幽默”的项目。
但正如其他人所说,最好有一个单独的标签表。为此,您还需要一个数据透视表。
例如
You can use
LIKE
Which will search for any entry where 'humor' is a substring. Note this will also return items tagged 'humorous'.
But like others said, having a separate table for tags would be best. To do this you will also need a pivot table.
So for example
为了扩展 Tomalak 的评论,最好使用
数据库
到标签
关系的多对多关系来解决这个问题。这涉及添加两个新表。像这样的东西(原谅我生锈的MySQL)然后,要查找与标签“幽默”匹配的所有
数据库
记录,您的查询将如下所示To expand on Tomalak's comment, this would be best solved using a many-to-many relationship for
database
totag
relationships. This involves adding two new tables. Something like this (forgive my rusty MySQL)Then, to find all the
database
records matching tag "humour", your query would look like