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
https://forums.phpfreaks.com/topic/82425-solved-foreign-keys-question/
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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.