Jump to content

[SOLVED] Identifying select elements that exist in another table.


jyushinx

Recommended Posts

So this is my issue:

 

I have a table that houses a large number of Items. There is another table that houses award information for certain items. This table is essentially comprised of ItemId and AwardId. I need a single query statement that will mark which items have awards when a generic list of items is requested. The purpose would be to include a special graphic next to the items that have awards. This is basically a statement that will let me know if each element exists in another table.

 

Thanks.

 

 

Link to comment
Share on other sites

I figured it would be with a LEFT JOIN, but when I was trying it out, I couldn't get it to work correctly.

 

Let's do an example...

 

Say we are doing a search for elements in the Items table that are of CategoryType 2. Now of these returned elements, we need to know which ones have won awards. So the basic SQL (without the LEFT JOIN) would be:

 

SELECT ItemName,ItemPrice,ItemDescription FROM ItemsTable WHERE CategoryType=2

 

What would the SQL be  so we ended up with another column that designates whether or not the item won an award?

 

Thanks.

Link to comment
Share on other sites

  • 1 month later...

Sorry for the extreme delay. I've been away. I wanted to post that Barand's solution plus an additional tweak solved the issue.

 

Because certain items can win multiple awards, and I wanted only distinct items returned, I added a GROUP BY. So:

 

SELECT lj.* FROM (SELECT i.id, i.ItemName, i.ItemPrice, i.ItemDescription, a.awardid
FROM ItemsTable i
LEFT JOIN awards_table a ON i.id = a.itemid
WHERE CategoryType=2) AS lj GROUP BY lj.id

 

 

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.