gvp16 Posted February 16, 2012 Share Posted February 16, 2012 Hi, i have 2 tables content which has : content_id, content_title,content_body eg. (1,this is a test, information about the test) and content_options which as : content_id, option, value eg. (1,price,29.99) (1,weight,15kg) (1,sale,yes) i know you can do something like, SELECT content_options.value AS price WHERE content_options.option = "price" which would give me price 29.99 by how can i join to the two in a single query? eg. get a result like : content_id | content_title | content_body | price | weight | sale 1 this is a test this is informaton about the test 29.99 15kg yes Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/257123-help-with-alias/ Share on other sites More sharing options...
requinix Posted February 16, 2012 Share Posted February 16, 2012 Two methods. The one I prefer is to use some JOINs SELECT c.content_id, c.content_title, c.content_body, co_p.value AS price, co_w.value AS weight, co_s.value AS sale FROM content c LEFT JOIN content_options co_p ON c.content_id = co_p.content_id AND co_p.option = "price" LEFT JOIN content_options co_w ON c.content_id = co_w.content_id AND co_w.option = "weight" LEFT JOIN content_options co_s ON c.content_id = co_s.content_id AND co_s.option = "sale" (outer joins, just in case the price/weight/sale value is missing) and the other is subqueries SELECT c.content_id, c.content_title, c.content_body, (SELECT value FROM content_options co WHERE co.content_id = c.content_id AND co.option = "price") AS price, (SELECT value FROM content_options co WHERE co.content_id = c.content_id AND co.option = "weight") AS weight, (SELECT value FROM content_options co WHERE co.content_id = c.content_id AND co.option = "sale") AS sale, FROM content c Quote Link to comment https://forums.phpfreaks.com/topic/257123-help-with-alias/#findComment-1318087 Share on other sites More sharing options...
gvp16 Posted February 17, 2012 Author Share Posted February 17, 2012 Excellent, thanks very much, i spent a few hours yesterday trying to figure it out! Is there one method you would pick out of the 2? eg. performance etc... Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/257123-help-with-alias/#findComment-1318285 Share on other sites More sharing options...
Muddy_Funster Posted February 17, 2012 Share Posted February 17, 2012 Use JOINS over subqueries. Quote Link to comment https://forums.phpfreaks.com/topic/257123-help-with-alias/#findComment-1318301 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.