Jump to content

Join two tables


ztimer

Recommended Posts

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

post-100402-0-31685800-1386959625_thumb.png
 

2. tweet

post-100402-0-50057600-1386959641_thumb.png

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.

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.