2

我正在尝试使用自定义查询获取 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 查询。但如果有人能给我解决这个问题,我将非常感激。

4

1 回答 1

6

您可以LEFT JOIN针对只返回那些确实有的子查询private_spaces_post,并寻找NULLs

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
于 2012-12-03T18:25:56.070 回答