Jump to content

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/257123-help-with-alias/
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/257123-help-with-alias/#findComment-1318087
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.