Question

How can I run a select query on a multivalue attribute? Does mysql have a function do select certain data from a multivalue field? Much help is appreciated. Here's a sample of the problem:

Table

userid      groups
-------------------
  2          2,3,5
  4          1
  9          2,5,10

datatype is char(250) for groups

I want to do a query to select all userids that belong to group 5, in this example it would be userid 2 and 9. So:

userid
------
  2
  9

Any way to go about it with a mysql query? or with php/mysql?

Was it helpful?

Solution

In case the groups datatype is SET

You can use

SELECT * FROM users WHERE FIND_IN_SET('5', groups);

UPDATE

In case of char or varchar. You can use this

SELECT * FROM users
WHERE 
     groups LIKE '5,%'
     OR groups LIKE '%,5'
     OR groups LIKE '%,5,%'
     OR groups = '5'

OTHER TIPS

This is ugly, but if you want to do it completely in MySQL, you could do:

SELECT *
FROM users
WHERE groups LIKE '%,5,%'
OR groups = '5'
OR groups LIKE '%,5'
OR groups LIKE '5,%'

You'd be better off having a separate table with one group per row and a reference back to the user. You could do a join with a much simpler condition with that schema.

SELECT users.*
FROM users
INNER JOIN users_groups ON (users.user_id = users_groups.group_id)
WHERE users_groups.group_id = 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top