Jump to content

Having trouble understanding joins


subnet_rx

Recommended Posts

I have two tables.  One has items, one has items ordered.  I want to list all the items, but if the current user ordered one of the items, I'd like to place a check by it.  The output would use several columns from the items table, and basically show a check if the corresponding item is found in the items ordered under the user's id.  I'm unsure how joins work, even after looking at a tutorial here and the SQL book I have on my desk.  Can someone either point me to a good explanation or point me in the right direction? 

 

Link to comment
Share on other sites

There are two common types of join

 

A JOIN (or INNER JOIN) will return rows only where rows in both tables match on a common key value.

 

In your case though, you need the second type, LEFT JOIN, to list all items whether a match exists or not. Where there isn't a match in the items_ordered table, all its columns in the result set contain NULL values.

 

So

 

SELECT i.item_name, o.user_id

FROM items i LEFT JOIN items_ordered o

ON i.item_id = o.item_id AND o.user_id = '$user_id'

 

When you process the result set, if the user_id col has a non-null value, then show it as checked

Link to comment
Share on other sites

ok, thanks.  For some reason, I was trying to figure out how I could access the value if both had the same column name.  But after I think about, I have no idea why I'd want to do that.  That's one of my problems, I get confused about something and start trying to figure out problems that have nothing to do with my current one.  Sometimes it helps me understand, others it just gets me lost.

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.