dan_e
dan_e

Reputation: 53

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.

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. I am stuck. Any ideas?

Thanks!

Upvotes: 0

Views: 169

Answers (1)

GMB
GMB

Reputation: 222432

You could pass your parameters as a derived table and then use find_in_set() to search the csv column:

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:

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. You should be storing each value of the each list on a separate row.

Upvotes: 1

Related Questions