I’m using this sql to return results based on an inner join with 3 meta values. It only seems to work with 1 AND ( ), when i add the other two it returns 0 results.
SELECT * FROM wp_posts
INNER JOIN wp_postmeta
ON ( wp_posts.ID = wp_postmeta.post_id )
WHERE wp_posts.post_type = 'plot'
AND wp_posts.post_status = 'publish'
AND ( wp_postmeta.meta_key = 'plot_type' AND wp_postmeta.meta_value = 'Cottage' )
AND ( wp_postmeta.meta_key = 'number_of_bedrooms' AND wp_postmeta.meta_value = '2' )
AND ( wp_postmeta.meta_key = 'property' AND wp_postmeta.meta_value = '446' )
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_title ASC;
I think you meant to use OR with the other 2 (see below). The same field can’t be 2 different things, which is why you get 0 results.
edit, try below instead:
You need to join the wp_postmeta table once for each type of value you need.
This
wp_postmeta
key/value storage is a little tricky to join to; your join criteria need to pull the appropriate key as well as the matching post ID.It’s well known that
SELECT *
is a bad idea in software. It’s especially bad when you’re joining so many tables. List the columns you need in your result set.Notice also that you’re using
INNER JOIN
with whichJOIN
is synonymous. If any of the values you’re pulling from the metadata are missing, so will be the row from your result set. You may or may not be better off using LEFT JOINs (You didn’t explain the purpose of the query.)It seems as some of the structure for your conditions should be changed.
Try the following:
I managed to fix the issue using WP_Meta_Query, the SQL it produced was…
Thanks to everyone for the help 🙂