Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select where equal to multiple values

Tags:

select

mysql

I have two databases, where I store who is following who and another which stores the posts the user makes.

I want to select all of the people a user is following from the following database and echo out the usernames of those who that user is following and query the posts database for posts of that user.

My problem is what if a user is following multiple users, I echoed out of the user id's of the people this user is following and I get 44443344330

When I separate each id with commans, I get:

44,44,33,44,33,0, 

so let's give that a variable of $user_ids;

$user_ids = "44,44,33,44,33,0, ";

the query:

$get_posts = mysql_query("SELECT * FROM posts WHERE userid = '$user_ids'");

but all it does is show the records of the first user id, 44.

How can I retrieve all of the records for all the users?

like image 209
frank Avatar asked Jul 29 '11 18:07

frank


People also ask

How can I get multiple values in MySQL?

To select multiple values, you can use where clause with OR and IN operator.

How do I select multiple values from the same column in MySQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);

WHERE clause pass multiple values?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.


3 Answers

The query should be:

SELECT * FROM posts WHERE userid IN (44,44,33,44,33,0)

However, you may have to rethink your data model and make sure it is normalized, so that you can express this construction directly in the databse without echoing into a comma-separated string.

Why do you have two databases? Do you mean two tables?

like image 76
Kerrek SB Avatar answered Oct 23 '22 13:10

Kerrek SB


Maybe you want to use IN

SELECT * FROM posts WHERE userid IN ($user_ids)
like image 33
james_bond Avatar answered Oct 23 '22 15:10

james_bond


Given that you have two tables, not two databases, the easiest way to match multiple values for a specific column would be the following:

SELECT * FROM posts WHERE userid IN (44,44,33,44,33,0)

*A small point that I ran into when doing this. If you are matching to a column that is of type VARCHAR(n), be sure to wrap your matching values in 'single quotes', not "double quotes"

e.g:

SELECT * FROM posts WHERE name IN ('foo','bar','alpha','beta')
like image 25
Callum Avatar answered Oct 23 '22 13:10

Callum