好的,所以我需要编写一个数据库查询,根据key b
和key_a
的值,从category
中获取meta_value。
这是我的sql:
$cat = $post['cat'];
$adh = $post['adhesion'];
//get adhesions for category
$query = $wpdb->get_results(
"SELECT p.`ID`, pm.`meta_value` FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} `p` ON `p`.`ID` = pm.`post_id`
LEFT JOIN {$wpdb->term_relationships} `tr` ON `p`.`ID` = `tr`.`object_id`
LEFT JOIN {$wpdb->term_taxonomy} `tt` ON `tr`.`term_taxonomy_id` = `tt`.`term_taxonomy_id`
WHERE `pm`.`meta_key` = 'substrate_box'
AND `pm`.`meta_key` = 'adhesion_box'
AND `pm`.`meta_value` = '$adh'
AND `p`.`post_status` = 'publish'
AND `p`.`post_type` = 'post'
AND `tt`.`taxonomy` = 'category'
AND `tt`.`term_id` = $cat
");
我需要做的是为每个包含类别值和第一个元键值(substrate_box
)的帖子获取meta_key adhesion_box
的值。
这个sql语句返回null,所以我不太清楚怎么做。
答案 0 :(得分:0)
将WHERE子句条件移动到ON子句。
SELECT p.`ID`, pm.`meta_value` FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} `p` ON `p`.`ID` = pm.`post_id`
LEFT JOIN {$wpdb->term_relationships} `tr` ON `p`.`ID` = `tr`.`object_id`
LEFT JOIN {$wpdb->term_taxonomy} `tt` ON `tr`.`term_taxonomy_id` = `tt`.`term_taxonomy_id`
AND `pm`.`meta_key` = 'substrate_box'
AND `pm`.`meta_key` = 'adhesion_box'
AND `pm`.`meta_value` = '$adh'
AND `p`.`post_status` = 'publish'
AND `p`.`post_type` = 'post'
AND `tt`.`taxonomy` = 'category'
AND `tt`.`term_id` = $cat
答案 1 :(得分:0)
这是最终工作的解决方案,原谅其丑陋:
$cat = $post['cat'];
$adh = $post['adhesion'];
//get adhesions for category
$query = $wpdb->get_results("
SELECT pm.`post_id` FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} `p` ON `p`.`ID` = pm.`post_id`
LEFT JOIN {$wpdb->term_relationships} `tr` ON `p`.`ID` = `tr`.`object_id`
LEFT JOIN {$wpdb->term_taxonomy} `tt` ON `tr`.`term_taxonomy_id` = `tt`.`term_taxonomy_id`
WHERE `pm`.`meta_key` = 'adhesion_box'
AND `pm`.`meta_value` = '$adh'
AND `p`.`post_status` = 'publish'
AND `p`.`post_type` = 'post'
AND `tt`.`taxonomy` = 'category'
AND `tt`.`term_id` = $cat
");
if(is_array($query)){
foreach($query as $obj){
$tmps = $wpdb->get_results("
SELECT p.`ID` as post_id, pm.`meta_value` FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} `p` ON `p`.`ID` = pm.`post_id`
WHERE pm.`post_id` = {$obj->post_id}
AND pm.`meta_key` = 'substrate_box'
");
if(is_array($tmps) && count($tmps) > 0){
foreach($tmps as $tmp){
$return[$tmp->post_id] = $tmp->meta_value;
}
}
}
}
这将根据帖子类别和第一个元值选择并返回第二个元值。