Skip to content
Advertisement

SQL: How to search set datatype by array?

I want to know if the data exist in set datatype by using an array.

For example: The table is

$role = [‘a’]

SQL = SELECT * FROM ... WHERE $role in role (have ‘a’)

And the result is

Or $role = [‘a’,’b’]

SQL = SELECT * FROM ... WHERE $role in role (have ‘a’ and ‘b’)

And the result is

I tried to use FIND_IN_SET(('a','b'),role)>0; but it’s not work. I need to use a loop. Have any method better than this?

Advertisement

Answer

MySQL doesn’t have an array type. What you are using is a string, that happens to contain commas.

The better method in a relational database is to store multi-valued attributes in a second table, with one value per row.

If you need to find an entry that has both role ‘a’ and role ‘b’, this is called . There are several solutions when using a normalized table. Here’s one:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement