Jump to content

[SOLVED] Foreign keys question


frikus

Recommended Posts

I have two simple tables with the following fields:

 

1. 'items' : item_id, item_name, external_color_id, internal_color_id

2. 'colors' : color_id, color_name

 

external_color_id and internal_color_id are foreign keys to the 'colors' table.

 

How can I get both external and internal color names of the item with only one query?

 

I came up with the following query but I know that it's wrong:

 

SELECT items.*, colors.color_name AS c1, colors.color_name AS c2
FROM items, colors
WHERE items.item_id = 100
AND items.external_color_id = colors.id 
AND items.internal_color_id = colors.id 

Link to comment
Share on other sites

You need to join the colors table twice (untested):

 

SELECT i.*, ci.color_name AS c1, ce.color_name AS c2
FROM items AS i
INNER JOIN colors AS ci ON ( i.internal_color_id = ci.id  )
INNER JOIN colors AS ce ON ( i.external_color_id = ce.id  )
WHERE i.item_id = 100

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.