2014-09-29 60 views
0

好吧,所以我需要編寫一個數據庫查詢以基於key_acategory的值得出key b中的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 
      "); 

我需要做的就是在meta_key substrate_box的價值有兩個類別值和第一元鍵值(adhesion_box),每一個崗位。

此sql語句返回null,所以我不太確定如何去做。

回答

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; 
       } 
      } 
     } 
    } 

這將選擇並返回立足崗位類別和第一元值的第二meta值。

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 
+0

它應該是'AND'而不是雙'ON' – 2014-09-29 15:58:38

+0

@RahilWazir,謝謝糾正它。 – radar 2014-09-29 16:02:42

+0

這會轉儲很多東西,而且它們都不是正確的元數據。這會拉動網站標題等所有內容,但不會從'meta_key'「substrate_box」獲取任何信息。 – 2014-09-29 16:40:26