MySQL where column = 'x, y, z'

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

I have an array in PHP:

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

anyway, you need to select all messages, where user_id = one of these values ​​without a massive request:

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

(I need to get messages from over 100 people to be ineffective)

thanks

+6
source share
5 answers

This is easy to do:

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

Since your value is in an array, you can use:

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

Hope this helps.

+6
source

Yes! You can use the IN statement:

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

If your array is always safe and contains elements, you can do:

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

in php too.

+8
source

Use the IN clause.

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

You may not like the keyword IN . Instead, you can use the regex as follows:

  select * from your_table where user_id regexp '1 | 2 | 3'
+2
source
 user_id >= 1 AND <= 3 

This is one of the alternatives.

+1
source

Source: https://habr.com/ru/post/907243/


All Articles