php - How to query posts by all friends of a user (stored between 3 MySQL tables)? -


so have user information, user-posted content , friends 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 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 specific user, user_content stores content posted user , friends stores 'friend' associations between users.

my question is, how query data user_content friends of particular user sorted date? loop through each friend of particular user:

$stmt = $mysqli->prepare("select user_id_1, user_id_2 friends 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 user, , friend     $friendid = $db_user_id_1;     if ($userid == $db_user_id_1) {         $friendid = $db_user_id_2;     }      //load latest 10 user_content each user, store in memory , sort date } $stmt->close(); 

but possible in single mysql query? overhead of looping through every friend , sorting date seems overkill. want latest 30 user_content friends of particular user.

select user_content inner joined on friends, grabbing content either user user_content record not belong current user current user 1 of friends... or @ query

edit: forgot add limit last 30 posts

select      uc.user_id friend_user_id     ,u.username friend_username     ,u.email friend_email     ,uc.date     ,uc.text user_content uc inner join friends f on uc.user_id in (f.user_id_1,f.user_id_2) inner join user u on uc.user_id = u.id uc.user_id != ? , ? in (f.user_id_1, f.user_id2) order date desc limit 30; 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -