3

我正在编写 sql 查询以根据分类和发布元数据获取帖子,现在我有这个

<?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查询中加入两者,希望有人能帮助我。

4

1 回答 1

5

尝试使用附加字段INNER JOIN连接表,以便它只连接相应的行post_metameta_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
于 2013-07-11T08:46:15.297 回答