frikus Posted December 20, 2007 Share Posted December 20, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/82425-solved-foreign-keys-question/ Share on other sites More sharing options...
fenway Posted December 20, 2007 Share Posted December 20, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/82425-solved-foreign-keys-question/#findComment-419675 Share on other sites More sharing options...
frikus Posted December 20, 2007 Author Share Posted December 20, 2007 You are using two similar tables for colors: 'ci' and 'ce' in your query. Is it the optimal way? Is there a way to use only one 'colors' table in double JOIN? Quote Link to comment https://forums.phpfreaks.com/topic/82425-solved-foreign-keys-question/#findComment-419837 Share on other sites More sharing options...
frikus Posted December 20, 2007 Author Share Posted December 20, 2007 Please disregard my last post. You are absolutely right. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/82425-solved-foreign-keys-question/#findComment-419948 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.