'MySQL where column = 'x, y, z'

Here's my situation: I need to select all the messages where user_id = x OR y OR z.

I have an array in PHP:

users = ('1', '2', '3')

is there anyway to select all the messages where user_id = one of those values without having a massive query of:

user_id = '1' OR user_id = '2' OR user_id = '3?'

(I need to receive the messages of 100+ people so it would be inefficient)

Thanks



Solution 1:[1]

Use an IN clause.

SELECT *
    FROM YourTable
    WHERE user_id IN ('1','2','3')

Solution 2:[2]

Yes! You can use the IN operator:

user_id IN ('1', '2', '3')

If your array will always be safe and contain elements, you can do:

"user_id IN ('" . implode("', '", $users) . "')"

in PHP, too.

Solution 3:[3]

Probably you don't like IN keyword. Instead, you can use a regular expression like this:

select * from your_table where user_id regexp '1|2|3'

Solution 4:[4]

user_id >= 1 AND <= 3 

Is one alternative.

Solution 5:[5]

before strings ids are:

$query = "SELECT * FROM table_name WHERE user_id IN('1','2','3')";

preformance int for ids:

$query = "SELECT * FROM table_name WHERE user_id IN(1,2,3)";

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe Stefanelli
Solution 2
Solution 3 mmdemirbas
Solution 4 IsisCode
Solution 5 Kamil DÄ…browski