Jump to content

Recommended Posts

Hi everyone,

 

One sentence was not enough to explain the problem so the title might not have made you fully understand the issue.

 

I am currently building an application, for which I will now describe the table structure (simplified).

 

TABLE posts

+---+----------+

| ID |    title  |

+---+----------+

|  1 |  Post 1  |

|  2 |  Post 2  |

|  3 |  Post 3  |

|  4 |  Post 4  |

+---+----------+

 

TABLE post_options

+---+------------+------------+------------+

| ID |  post_id  |    key      |    value    |

+---+------------+------------+------------+

|  1 |      2      |  brand    |    Sony    |

|  2 |      2      |    price    |      20      |

|  3 |      1      |    price    |      60      |

|  4 |      3      |    price    |      10      |

|  5 |      3      |    brand  |    ABC    |

+---+------------+------------+------------+

 

Now what I want is to add a search option to my website: people have to be able to search for posts where (for example) the brand is Sony and the price is 20. It is possible that more rows match, by the way.

 

What I tried was to JOIN post_options on posts, like so:

JOIN
	post_options
ON
	posts.ID=post_options.post_id

 

That went fine, so I wanted to search that (brand Sony, price 20), for which I tried:

SELECT
	ID,
	title
FROM
	posts
JOIN
	post_options
ON	
	posts.ID=post_options.post_id
WHERE
	post_options.key='brand'
AND	post_options.value='Sony'
AND	post_options.key='price'
AND	post_options.value='20'

 

Obviously, that didn't work, as MySQL doesn't know of course which key belongs to which value. The question is now: How to do this rightly?

 

How to return the posts for which there is one post option key 'brand' with value 'Sony' and one key 'price' with value '20', with matching post_id's?

 

 

Thanks in advance!

 

MySQL Version: 5.0.90-community

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.