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
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.
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.
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.
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 .
Use an IN clause.
SELECT *
FROM YourTable
WHERE user_id IN ('1','2','3')
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With