SELECT DISTINCT wposts.ID AS ID
FROM `wp_posts` AS wposts
JOIN `wp_postmeta` AS postmeta ON (wposts.ID = postmeta.post_id)
WHERE wposts.post_type = 'post'
AND wposts.ID NOT IN (
SELECT wp_posts.ID FROM wp_posts, `wp_postmeta` AS postmeta2
WHERE wp_posts.ID = postmeta2.post_id
AND postmeta2.meta_key = 'z_latitude'
)
ORDER BY wposts.post_date DESC
The query is a mess. I simply want to query all rows that do 开发者_运维技巧not have a certain meta key. Above, I query all rows that have the meta key and then exclude them from the outer query. I don't know how to write this better.
Use an outer join via a left join
and grab rows that didn't join:
SELECT DISTINCT wposts.ID AS ID
FROM `doxy_posts` AS wposts
left JOIN `doxy_postmeta` AS postmeta ON wposts.ID = postmeta.post_id
WHERE postmeta.post_id is null
ORDER BY wposts.post_date DESC
SELECT wposts.ID AS ID
FROM doxy_posts AS wposts
LEFT JOIN doxy_postmeta AS postmeta
ON wposts.ID = postmeta.post_id
AND postmeta.meta_key = 'z_latitude'
WHERE wposts.post_type = 'post'
AND postmeta.post_id IS NULL
ORDER BY wposts.post_date DESC
or:
SELECT wposts.ID AS ID
FROM doxy_posts AS wposts
WHERE wposts.post_type = 'post'
AND NOT EXISTS
( SELECT *
FROM doxy_postmeta AS postmeta
WHERE wposts.ID = postmeta.post_id
AND postmeta.meta_key = 'z_latitude'
)
ORDER BY wposts.post_date DESC
精彩评论