So I have user information, user-posted content and friends all in separate tables.

Example data:

user:

```
id    username      email
1     userA         myemail@testa.com
2     userB         myemail@testb.com
3     userC         myemail@testc.com

```

user\_content

```
id    user_id      date                     text
1     1             2015-09-12 00:24:08     content here
2     2             2015-09-11 00:24:08     more content here a
3     1             2015-09-10 00:24:08     more content here b
4     3             2015-09-05 00:24:08     more content here c

```

friends

```
id    user_id_1  user_id_2
1     1          2
2     2          3
3     2          4

```

The `user` table store information about a specific user, `user_content` stores content posted by that user and `friends` stores 'friend' associations between users.

My question is, how would I query this data to get the user\_content for all friends of a particular user sorted by date? Currently I loop through each friend of a particular user:

```
$stmt = $mysqli->prepare("SELECT user_id_1, user_id_2 FROM friends WHERE user_id_1 = ? OR user_id_2 = ?");
$stmt->bind_param("ii", $userID, $userID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($db_user_id_1, $db_user_id_2);
while ($stmt->fetch()) {
    //Work out which is the user, and which is the friend
    $friendID = $db_user_id_1;
    if ($userID == $db_user_id_1) {
        $friendID = $db_user_id_2;
    }

    //Load latest 10 user_content for each user, store in memory and sort by date
}
$stmt->close();

```

But is this possible in a single MySQL query? The overhead of looping through every friend and then sorting by date seems overkill. I just want the latest 30 `user_content` for all friends of a particular user.