1

Supposing I have a MySQL table (meta_table) as follows with the following data:

meta_id,post_id,meta_key,meta_value
5,10,my_key1,value1
10,11,my_key2,value2
15,12,my_key3,value3
35,11,my_key4,value4

How can I get the post_id if meta_value is value2 and value4 (the answer should be 11). I have tried this:

SELECT post_id from meta_table where meta_value='value2' and meta_value='value4' 

But it does not return 11 as the post_id. Any suggestions?

1
  • Both Mahmoud's and Petah's answers should work. Can you have two different rows with post_id=11 and meta_value=value2? If yes then you might have to modify the answers slightly. Commented Dec 3, 2012 at 9:16

5 Answers 5

2

With a join:

SELECT a.post_id
FROM meta_table AS a
JOIN meta_table AS b ON a.post_id = b.post_id
WHERE a.meta_value = 'value2' AND b.meta_value = 'value4'

http://www.sqlfiddle.com/#!2/96d2b/4/0

Sign up to request clarification or add additional context in comments.

Comments

2
SELECT post_id
from meta_table 
where meta_value IN ('value2', 'value4')
GROUP BY post_id
HAVING COUNT(*) = 2;

SQL Fiddle Demo

2 Comments

Good answer, but is it better than a join?
You can use a JOIN, as per my answer. The reason to is because HAVING is a post filter condition, when using a JOIN + WHERE is pre-filtered and makes better use of indexes.
1

Try using OR

SELECT post_id from meta_table where meta_value='value2' OR meta_value='value4'

Or you can use IN

SELECT post_id from meta_table where meta_value IN ('value2', 'value4')

2 Comments

This will get the post_id that has value2 or value4. But I think the OP is looking for the post_ids that had both value2 and value4.
@MahmoudGamal Maybe. By the way I like your answer (+1)
0

It should be :

SELECT post_id from meta_table where meta_value='value2' or meta_value='value4'

Comments

0

query is : -

SELECT post_id from meta_table
where meta_value='value2' or meta_value='value4'
GROUP BY post_id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.