0

I want to select post_id where (meta_key = group_name and meta_value = Caucaia) and (meta_key = _featured and meta_value = 1)

Table: wp_postmeta

post_id | meta_key | meta_value
---------------------------
746     | group_name | Caucaia
746     | _featured  | 1
747     | group_name | Caucaia
747     | _featured  | 0
1791    | group_name | Aruba
1791    | _featured  | 1

I tried the below query but doesn't works

SELECT `post_id` FROM `wp_postmeta` WHERE (`meta_key` = 'group_name' and `meta_value` ='Caucaia' and `post_id` in (746, 747, 731, 1791, 1799)) or (`meta_key` = '_featured' and `meta_value` ='1' and `post_id` in (746, 747, 731, 1791, 1799)) GROUP BY `post_id`

How do I make query to select from multiple row? or is there any other way?

2 Answers 2

1

Use aggregation:

SELECT `post_id`
FROM `wp_postmeta`
WHERE (`meta_key` = 'group_name' and `meta_value` ='Caucaia' and `post_id` in (746, 747, 731, 1791, 1799)) or
      (`meta_key` = '_featured' and `meta_value` ='1' and `post_id` in (746, 747, 731, 1791, 1799))
GROUP BY `post_id`
HAVING COUNT(*) = 2;

Actually, I notice the two lists are the same. I would write this using list constructors:

SELECT `post_id`
FROM `wp_postmeta`
WHERE (post_id` in (746, 747, 731, 1791, 1799)) AND
      (meta_key, meta_value) IN (('group_name', 'Caucaia'), ('_featured', '1'))
GROUP BY `post_id`
HAVING COUNT(*) = 2;
Sign up to request clarification or add additional context in comments.

Comments

0

Once way to do this is to have a where clause with all the combinations you need, and count the number of rows it returns:

SELECT   post_id
FROM     wp_postmeta
WHERE    (meta_key = 'group_name' AND meta_value = 'Caucaia') OR 
         (meta_key = '_featured' AND meta_value = '1')
GROUP BY post_id
HAVING   COUNT(*) = 2

1 Comment

did you forget the IN section?

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.