0

我需要从几个 WP 表中选择一些东西,其中之一是具有特定键的自定义字段值。问题是,一些帖子没有带有此键的自定义字段,但除此之外它们匹配查询。所以问题是,我如何选择甚至没有带有此键的自定义字段的帖子,但除了匹配查询之外?没有自定义字段的帖子的字段值应设置为 0。我认为它类似于 COALESCE,但我要么使用错误,要么在这种情况下无法使用。到目前为止,我的查询是:

select lists.id,lists.`type`,lists.`status`,lists.watched_eps, lists.score,wp_posts.post_title,wp_posts.post_name,wp_terms.slug,wp_postmeta.meta_value from anime_lists
INNER JOIN wp_posts ON (wp_posts.ID = lists.post_id ) 
INNER JOIN wp_postmeta ON (wp_postmeta.post_id= lists.post_id )
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 
INNER JOIN wp_term_taxonomy ON(wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
INNER JOIN wp_terms ON(wp_terms.term_id = wp_term_taxonomy.term_id)
where lists.id=1
and wp_term_taxonomy.taxonomy = 'category'
and wp_postmeta.meta_key='eps'
group by lists.`post_id`
order by lists.`status`, wp_posts.post_title

实际上,查询输出我需要的所有内容,但没有这些没有自定义字段“eps”的帖子。如果我删除and wp_postmeta.meta_key='eps'它会输出这些帖子,但这样我会在wp_postmeta.meta_value字段中得到错误的值。

4

1 回答 1

3

据我了解您想要什么,您只需将 wp_postmeta 联接更改为 aLEFT JOIN并将WHERE该表上的条件移至联接,然后离开;

SELECT lists.id, lists.`type`, lists.`status`, lists.watched_eps, 
       lists.score,wp_posts.post_title,wp_posts.post_name,wp_terms.slug,
       wp_postmeta.meta_value 
FROM anime_lists
INNER JOIN wp_posts 
  ON wp_posts.ID = anime_lists.post_id
LEFT JOIN wp_postmeta 
  ON wp_postmeta.post_id = anime_lists.post_id 
 AND wp_postmeta.meta_key='eps'
INNER JOIN wp_term_relationships 
  ON (wp_posts.ID = wp_term_relationships.object_id) 
INNER JOIN wp_term_taxonomy 
  ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
INNER JOIN wp_terms 
  ON(wp_terms.term_id = wp_term_taxonomy.term_id)
WHERE lists.id=1
  AND wp_term_taxonomy.taxonomy = 'category'
GROUP BY lists.`post_id`
ORDER BY lists.`status`, wp_posts.post_title
于 2013-08-15T20:28:32.070 回答