ztimer Posted December 13, 2013 Share Posted December 13, 2013 I have a problem figuring out how to join two tables and still get the session user id text-s also.I have two tables. 1. follow 2. tweet On the page i have $_SESSION['user_id'] - The user that is loged in for example "1".The idea is to get a table of the tweets and limit the results from the $_SESSION['user_id'] and the follow_user_id -s from the follow table.I figured i must join the two tables. This works but i cant seem to add the session user to the mix.My MYSQL query so far $sql="SELECT * FROM tweet JOIN follow ON tweet.user_id=follow_user_id WHERE follow.user_id = '".$_SESSION['user_id']."' ORDER BY date_time desc"; I have no idea how to add the text rows from tweets that have the session user_id also to the mix. Please can someone lend a hand.Thanks for your help. Quote Link to comment https://forums.phpfreaks.com/topic/284748-join-two-tables/ Share on other sites More sharing options...
PravinS Posted December 14, 2013 Share Posted December 14, 2013 may LEFT JOIN will help you $sql="SELECT * FROM tweet LEFT JOIN follow ON tweet.user_id=follow.user_id WHERE follow.user_id = '".$_SESSION['user_id']."' ORDER BY date_time desc"; Quote Link to comment https://forums.phpfreaks.com/topic/284748-join-two-tables/#findComment-1462317 Share on other sites More sharing options...
DavidAM Posted December 14, 2013 Share Posted December 14, 2013 Your query gets the tweets of the the users being followed by the logged in user. We just need to add an OR clause to get the tweets of the logged in user. $sql = "SELECT * FROM tweet LEFT JOIN follow ON tweet.user_id=follow_user_id WHERE follow.user_id = " . $_SESSION['user_id'] . " OR tweet.user_id = " $_SESSION['user_id'] . " ORDER BY date_time desc";Notes:1) If the IDs (user_id, follow_user_id) are defined as integers (in the database), you do not need to wrap them in quotes (in the query). 2) Don't use SELECT *, select only the columns you actually need. 3) We need the LEFT JOIN just in case nobody is following the logged in user. 4) If the tables get really big, this may not be the most efficient query. You might have to look at a UNION query instead of the OR Quote Link to comment https://forums.phpfreaks.com/topic/284748-join-two-tables/#findComment-1462338 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.