[英]Select rows where any of field's values matches values from array
I have a pretty complicated task.我有一个非常复杂的任务。 I need to select rows which match any of an array's value - BUT the field contains many comma-seperated values as well.我需要选择匹配任何数组值的行 - 但该字段也包含许多逗号分隔的值。
$teamlist = "25,26,27,28,29,30"
MYSQL-Row 1 = "26,29,31,35,36"
MYSQL-Row 2 = "30,31,32,36,39"
MYSQL-Row 3 = "31,35,36,37,38"
MYSQL-Row 4 = "23,26,29,30,31"
As result Rows 1,2 and 4 should be selected.因此应选择第 1,2 和 4 行。
I tried something like:我试过类似的东西:
mysqli_query($con,"SELECT * FROM user_meta WHERE team IN '".$ids."'");
But that only works if the fields only contain one id, not multiple.但这仅适用于字段仅包含一个 ID 而不是多个 ID 的情况。 I am stuck.我被困住了。 Any ideas?有任何想法吗?
Thanks!谢谢!
You could pass your parameters as a derived table and then use find_in_set()
to search the csv column:您可以将参数作为派生表传递,然后使用find_in_set()
搜索 csv 列:
select t.*
from mytable t
inner join (
select 25 team_id
union all select 26
union all select 27
...
) x on find_in_set(x.team_id, t.team)
This leaves you with the work of building the derived table from your application.这留给您从应用程序构建派生表的工作。 In very recent versions of MySQL, the VALUES()
statement makes the task a litte easier:在最新版本的 MySQL 中, VALUES()
语句使任务变得更容易:
select t.*
from mytable t
inner join (values row(26),row(27), ...) x(team_id)
on find_in_set(x.team_id, t.team)
However, you should not be storing lists in a database columns.但是,您不应将列表存储在数据库列中。 This is hurtful in many ways, as explained in this famous SO answer .正如在这个著名的 SO answer 中所解释的那样,这在很多方面都是有害的。 You should be storing each value of the each list on a separate row.您应该将每个列表的每个值存储在单独的行中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.