多个WHERE查询

I am making a news feed page like in Facebook, Twitter, or any other social media sites out there.

My problem is I need to get all the user id's of each user's friends, then use all those values to query another table that has all the new updates.

So, let's say I have 3 friends (1,2,3). I want to search another table using all 3 values in my WHERE clause in the same query so that I can order it by date.

The way I've done it so far puts all the id's into an array and uses a foreach loop to query my db for every value I have, but this groups all the results based on the order of user id in the array, so my results come out like this 11111,222222,333333 instead of the time the update was made. So, even if 3 makes an update days before 1 or 2, it will always come after two.

I am aware this might not be the best way to do it, but so far it's the only method I can think of.

Please any assistance you could provide would be greatly appreciated.

My code:

$id = $_SESSION['id'];
$update = mysql_query("
    SELECT profile_id FROM `fiends` 
    WHERE `my_fiend_id` = '$id'
    ");
$result = $update;
$fiends = array();

while (($row = mysql_fetch_assoc($result)) !== false) {
    $fiends[] = array(
        'id' => $row['profile_id'],
);}

foreach($fiends as $fiend) {
    $fiend_id = $fiend['id'];
    $update_select = mysql_query("          
        SELECT * FROM `update` 
        WHERE `NU_id` = '$fiend_id'                 
        ORDER BY `time` DESC
        ");

$result = $update_select;

You should turn this into one query

SELECT `update`.*
FROM `update`
INNER JOIN `fiends` ON update.`NU_id` = fiends.`my_fiend_id`
WHERE `my_fiend_id` = '$id'              
ORDER BY `time` DESC

Alternatively, you can use an IN () statement

"SELECT * FROM `update` WHERE `NU_id` = IN ('".join(',', $fiend_id)."')"

Your final statement would look something like this

WHERE `NU_id` IN (11111,222222,333333)

If the NU_ID is a varchar column then make sure to use quotes around the values

WHERE `NU_id` IN ('11111','222222','333333)

I would recommed you use an inner join on the SQL query instead of using a PHP loop. MySQL is faster, than a PHP loop.

Try this simpler version first

SELECT friends.profile_id, update.* 
FROM `fiends`, `update` 
WHERE `my_fiend_id` = '$id'
AND `NU_id` = `my_fiend_id`                 
ORDER BY `time` DESC