如何加入post meta和taxonomy表wpdb mysql

时间:2013-07-11 08:25:16

标签: php mysql wordpress taxonomy

我正在编写sql查询以基于分类和post meta获取帖子,现在我有了这个

<?php
$querystr = "
SELECT * 
FROM $wpdb->posts as m,$wpdb->postmeta
LEFT JOIN $wpdb->term_relationships ON(m.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)  
WHERE m.post_type = 'holiday' 
AND $wpdb->posts.ID = $wpdb->postmeta.post_id 
AND $wpdb->postmeta.meta_key = 'repeatable_fields' 
AND $wpdb->postmeta.meta_value like '%July%' 
AND m.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = 'location'
AND $wpdb->terms.slug = 'berlin' OR $wpdb->terms.slug = 'canada'
ORDER BY m.post_date DESC
 "; ?>

但即使我有基于上述评论的帖子,它也显示空结果。每个表单独使用下面的查询,

SELECT $wpdb->posts.* 
    FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
    AND $wpdb->postmeta.meta_key = 'repeatable_fields' 
    AND $wpdb->postmeta.meta_value like '%July%' 
    AND $wpdb->posts.post_status = 'publish' 
    AND $wpdb->posts.post_type = 'holiday'
    AND $wpdb->posts.post_date < NOW()
    ORDER BY $wpdb->posts.post_date DESC

和分类

SELECT * 
    FROM $wpdb->posts as m
LEFT JOIN $wpdb->term_relationships ON(m.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)  
WHERE m.post_type = 'holiday' 
AND m.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = 'location'
AND $wpdb->terms.slug = 'berlin' OR $wpdb->terms.slug = 'canada'
ORDER BY m.post_date DESC
 ";

但如何在单个sql查询中加入,希望有人帮助我。

1 个答案:

答案 0 :(得分:5)

尝试使用INNER JOIN并将post_meta表加入附加字段meta_key,以便它只会加入相应的行

SELECT * FROM `wp_posts` wp
INNER JOIN `wp_postmeta` wm ON (wm.`post_id` = wp.`ID` AND wm.`meta_key`='repeatable_fields')
INNER JOIN `wp_term_relationships` wtr ON (wp.`ID` = wtr.`object_id`)
INNER JOIN `wp_term_taxonomy` wtt ON (wtr.`term_taxonomy_id` = wtt.`term_taxonomy_id`)
INNER JOIN `wp_terms` wt ON (wt.`term_id` = wtt.`term_id`)
AND wtt.taxonomy = 'location' AND wt.`slug`IN ('berlin','canada')
AND wp.post_status = 'publish' AND wm.meta_value LIKE '%July%' 
ORDER BY wp.post_date DESC