查询不存在元数据键的行

时间:2011-06-26 09:44:47

标签: mysql

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

查询很乱。我只想查询没有某个元键的所有行。 在上面,我查询具有元键的所有行,然后将它们从外部查询中排除。 我不知道如何写得更好。

2 个答案:

答案 0 :(得分:1)

通过left 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

答案 1 :(得分:0)

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

或:

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