在 MySQL ListOfValues 中查询匹配项

发布于 2024-08-07 18:47:52 字数 346 浏览 3 评论 0原文

当我希望查询返回值列表中至少一个值与值列表中至少一个值匹配的所有行时,查询 MySql 的最佳方法是什么?

示例

如果我的表包含以下行:

name         groups
item1        gr1, gr2
item2        gr1,gr2,gr3
item3        gr1,gr3

并且我有一个值列表:“gr3,gr4,gr5”

我想查找表中至少具有值 gr3、gr4 或 gr5 之一的所有行场地。

因此,本例中的查询应返回 item2 和 item3

如何在脚本中不循环的情况下构造有效的查询?

Whats the best way to query MySql when I want the query return all rows where at least one value in a list of values matches at least one value in a list of values?

example

If my table contains the following rows:

name         groups
item1        gr1, gr2
item2        gr1,gr2,gr3
item3        gr1,gr3

And I have a list of values: "gr3,gr4,gr5"

I want to find all the rows in my table that have at least one of the values gr3,gr4 or gr5 in its groups field.

So the query in this case should return item2 and item3

How can I construct an efficient query without looping in my script?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娇纵 2024-08-14 18:47:52

我个人认为这不是构建数据库的最佳方法。我将有一个链接表,类似于 item_groups ,它将为每个项目组链接保存一行,因此您所拥有的将是:

item_name         group_name
item1        gr1
item1        gr2
item2        gr1
item2        gr2
item2        gr3
item3        gr1
item3        gr3

这样您就可以简单地执行

SELECT item_name FROM item_groups WHERE group_name IN ('gr3','gr4','gr5');

以下操作 这是我在介绍数据库理论作为我的理学学士,虽然它确实会产生更多的表格,但它使搜索变得更快更容易。
华泰

Personally I would suggest this isn't the best way to structure your database. I would have a link table, something like item_groups which would hold one row for each item-group link, so what you have there would be:

item_name         group_name
item1        gr1
item1        gr2
item2        gr1
item2        gr2
item2        gr3
item3        gr1
item3        gr3

This way you can simply do

SELECT item_name FROM item_groups WHERE group_name IN ('gr3','gr4','gr5');

This is what I was taught when I covered Database theory as part of my BSc, and whilst it does result in more tables, it makes searching a lot quicker and easier.
HTH

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文