Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL where column = 'x, y, z'

Tags:

php

mysql

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

like image 958
andy Avatar asked Jan 30 '12 15:01

andy


People also ask

How do I select a column in MySQL?

To select a column that is also a keyword in MySQL, you need to use backticks around the column name. As you know select is a keyword in MySQL, consider column name as select when creating a new table.

How can I see two columns in MySQL?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

How do I fill a column in MySQL?

First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.

How to CREATE TABLE with SELECT statement in MySQL?

You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement: CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl; MySQL creates new columns for all elements in the SELECT .


4 Answers

Use an IN clause.

SELECT *
    FROM YourTable
    WHERE user_id IN ('1','2','3')
like image 93
Joe Stefanelli Avatar answered Nov 04 '22 12:11

Joe Stefanelli


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.

like image 37
Ry- Avatar answered Nov 04 '22 13:11

Ry-


This is easy to do :

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

Since your value is in 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.

like image 6
Sabari Avatar answered Nov 04 '22 13:11

Sabari


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'
like image 2
mmdemirbas Avatar answered Nov 04 '22 13:11

mmdemirbas