php – 如何加入post meta和taxonomy表wpdb mysql
作者:互联网
即时通讯写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查询中加入两者,希望有人帮助我.
解决方法:
尝试使用INNER JOIN并使用附加字段meta_key加入post_meta表,以便它只加入相应的行
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
标签:taxonomy,php,mysql,wordpress 来源: https://codeday.me/bug/20190831/1777913.html