selecting from SQL with LEFT JOIN and multiple conditions

I am trying to fetch posts with multiple filters, my database is as below,

"Meta" Table

idmeta_keymeta_valueobject_nameobject_id
2locationnew citypost2
1post_typesectionpost2

meta table

"Posts" Table

idtitleexcerptdescriptionmime
_type
statusparentpost
_class
dtimesort
_id
author
_id
2testing-1post2021-04-12 03:06:0600
1test postsome descriptionactive-1post2021-04-12 12:09:3201

enter image description here

 SELECT p.id,90p.title FROM posts p LEFT JOIN meta m ON p.id = m.object_id and m.object_name='post' WHERE m.meta_key='location' and m.meta_value='new city' and m.meta_key='post_type' and m.meta_value='section' group by p.id

and I tried the above SQL but trouble is I am unable to form right conditional statement, i need to get all the post which have meta key 'post type' with value 'section' and meta key 'location' with value 'new city'.

this query does work with single filter though.

 SELECT p.id,90p.title FROM posts p LEFT JOIN meta m ON p.id = m.object_id and m.object_name='post' WHERE m.meta_key='location' and m.meta_value='new city' group by p.id
1

1 Answer

SELECT p.id, p.title
FROM posts p
JOIN meta m ON p.id = m.object_id
WHERE m.object_name='post' AND (m.meta_key, m.meta_value) IN ( ('location', 'new city'), ('post_type', 'section') )
GROUP BY p.id, p.title
HAVING COUNT(DISTINCT m.id) = 2
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like