Mysql查询,WP自定义字段

时间:2013-08-15 20:15:20

标签: mysql wordpress

我需要从几个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字段中输入错误值。

1 个答案:

答案 0 :(得分:3)

据我所知,你可以将你的wp_postmeta联接更改为LEFT 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