Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking value in an array inside one SQL query with WHERE clause

Tags:

I want to know is this practically possible in sql(using php as server-side), where in you have an array of values(numbers), and you try to retrieve data based on values inside that array..

I have a sql table:

posts(     id int(11) primary key,     posts varchar(140),     user_id int(11) foreign key ); 

I write a query now to retrieve 'posts':

$query="SELECT * FROM posts WHERE user_id=(**Array of select user_id's**)"; 

Is there any sql in-built function to check values inside an array? or should I be using PHP for this?

I am actually trying to implement the twitter model of showing posts of people whom we follow.

like image 258
Robbie Dc Avatar asked Nov 25 '11 13:11

Robbie Dc


People also ask

Can we use array in WHERE clause in SQL?

We can pass an array with the help of where IN clause.

Can we use array in WHERE clause?

Array can be passed in WHERE clause of sql query and in PLSQL as well.

How do I select an array value in SQL?

SELECT (array['one','two','three'])[state] FROM mytable WHERE id = 1; But as already stated, the CASE statement is the standard and portable method.

Can we use both WHERE and having in one select statement?

A query can contain both a WHERE clause and a HAVING clause. In that case: The WHERE clause is applied first to the individual rows in the tables or table-valued objects in the Diagram pane. Only the rows that meet the conditions in the WHERE clause are grouped.


2 Answers

Yes, this is easily possible. You need to look at MySQL's IN function

Your query would be something like

SELECT * FROM posts WHERE user_id IN (1,2,3,4,5,6) 

You can build the bit in between the parentheses in PHP using implode()

like image 189
liquorvicar Avatar answered Sep 20 '22 11:09

liquorvicar


SQL can't parse PHP arrays. Try this:

$query="SELECT * FROM posts WHERE user_id IN ({implode(',', $userIDarray)})"; 
like image 39
Hikaru-Shindo Avatar answered Sep 19 '22 11:09

Hikaru-Shindo