如果特定的meta_key不存在,wordpress自定义mysql查询仅获取帖子

时间:2012-12-03 18:22:49

标签: mysql sql wordpress categories

我正在尝试使用自定义查询获取wp帖子。这是sql查询:

SELECT p.*, IFNULL(SUM(vote), 0) AS vote_count, CAST(m.meta_value AS SIGNED) AS idea_count
FROM wp_posts p
INNER JOIN wp_term_relationships r ON p.ID=r.object_id
INNER JOIN wp_term_taxonomy t ON t.term_taxonomy_id=r.term_taxonomy_id AND t.taxonomy='category'
LEFT JOIN wp_wdpv_post_votes v ON v.post_id=p.ID
LEFT JOIN wp_postmeta m ON m.post_id=p.ID AND m.meta_key='ideas_count'
WHERE p.post_status='publish' AND p.post_type='post' AND t.term_id='5'
GROUP BY p.ID
ORDER BY p.ID DESC
LIMIT 0, 8

这个SQL查询工作正常。但现在我有另一个案例,我想要使用此查询显示帖子,但只显示没有特定元键的帖子。要过滤的元键是

'private_spaces_post'

这可能是mysql查询特有的。但如果有人能为我解决这个问题,我将非常感激。

1 个答案:

答案 0 :(得分:6)

您可LEFT JOIN针对仅返回具有private_spaces_post的子查询的子查询,并查找NULL s

SELECT p.*, IFNULL(SUM(vote), 0) AS vote_count, CAST(m.meta_value AS SIGNED) AS idea_count
FROM wp_posts p
  INNER JOIN wp_term_relationships r ON p.ID=r.object_id
  INNER JOIN wp_term_taxonomy t ON t.term_taxonomy_id=r.term_taxonomy_id AND t.taxonomy='category'
  LEFT JOIN wp_wdpv_post_votes v ON v.post_id=p.ID
  LEFT JOIN wp_postmeta m ON m.post_id=p.ID AND m.meta_key='ideas_count'
  /* LEFT JOIN subquery returning only ids that *do* have the meta key */
  LEFT JOIN (
    SELECT post_id FROM wp_postmeta WHERE meta_key='private_spaces_post'
  ) psp ON p.ID = psp.post_id
WHERE p.post_status='publish' AND p.post_type='post' AND t.term_id='5'
  /* And find post ids from the main table that *don't* have a match in the subquery (LEFT JOIN returns NULL) */
  AND psp.post_id IS NULL
GROUP BY p.ID
ORDER BY p.ID DESC
LIMIT 0, 8