1

I have 2 table - users and posts. I get users list with next sql request :

$sql = "SELECT user_id FROM users WHERE some_param = 1";
$result = mysql_query($sql);

$result - Array.

After how I can get element from posts with $result?

$sql2 = "SELECT * FROM posts where user_id in ($result)";
$result2 = mysql_query($sql2);

But don't work it, please help .

3 Answers 3

1

Use sub-queries to avoid running queries for multiple times.

Through this you can get expected data in one go.

$sql2 = "SELECT * FROM posts where user_id in (
SELECT user_id FROM users WHERE some_param = 1
)";
Sign up to request clarification or add additional context in comments.

Comments

1

You can also use a single query for this purpose by joining the tables

 $sql = "SELECT * FROM posts inner join users on users.user_id = posts.user_id  
        WHERE users.some_param = 1";

Comments

0

Use implode like

$sql2 = "SELECT * FROM posts 
         WHERE user_id IN (". implode(',',$result) .")";

Even you directly write the sub query like

$sql2 = "SELECT * FROM posts 
         WHERE user_id IN (SELECT user_id FROM users WHERE some_param = 1)";

Also so many result in this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.