开发者

Query rows for which meta data key does not exist

开发者 https://www.devze.com 2023-03-15 06:05 出处:网络
SELECT DISTINCT wposts.ID AS ID FROM `wp_posts` AS wposts JOIN `wp_postmeta` AS postmeta ON (wposts.ID = postmeta.post_id)
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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号