如何在wordpress中执行子查询

时间:2016-04-25 11:13:30

标签: php mysql wordpress

您好我需要执行一个查询来计算具有meta_key状态和meta_value的帖子,例如Unplaced,同一帖子有一个meta_key,如issue_date和meta_value,就像两天之间的日期一样。例如,我有一个这样的表:

id_meta post_id meta_key   meta_valuue
      1       1 status     Unplaced
      2       1 issue_date 20160428
      3       2 status     VIP
      4       2 issue_date 20160428
      5       3 status     Placed
      6       3 issue_date 20160427
      7       4 status     Unplaced
      8       4 issue_date 20160420

我希望查询只返回1,因为只有一个帖子的状态为Unplaced,issue_date的格式为21到28.我写的查询是:

$results = $wpdb->get_var(" 
SELECT COUNT(*) 
  FROM wp_posts
     , wp_postmeta 
 WHERE meta.key = 'status' 
   AND meta_value LIKE '%Unplaced%' 
   AND post_id = ID 
   AND post_status <> 'trash' 
   AND post_id IN ( SELECT post_id 
                      FROM wp_postmeta 
                     WHERE meta_key = 'issue_date' 
                       AND meta_value >= '20160421' 
                       AND meta_value <= '20160428')
");

我需要帖子不在垃圾桶里。

谢谢!!!!

2 个答案:

答案 0 :(得分:1)

您可以构建一个meta_query args并像这样传递给WP_Query

$args = array(
    'meta_query' => array(
        array(
            'key'     => 'status',
            'value'   => 'Unplaced',
            'compare' => '=',
        ),
        array(
            'key' => 'issue_date',
            'value'   => array( '2016-04-21', '2016-04-28' ),
            'type'    => 'date',
            'compare' => 'BETWEEN',
        ),
    ),
);
$query = new WP_Query( $args );

//Then get count like this
$query->found_posts;

类型DATE的格式应为YYYY-MM-DD,以便比较值BETWEEN

详细了解WP_Query here$found_posts here

答案 1 :(得分:0)

例如:

SELECT s.post_id
     , s.meta_value status
     , i.meta_value issue_date 
  FROM wp_posts s 
  JOIN wp_posts i 
    ON i.post_id = s.post_id 
 WHERE s.meta_key = 'status' 
   AND s.meta_value = 'Unplaced' 
   AND i.meta_key = 'issue_date' 
   AND i.meta_value BETWEEN '20160421' AND '20160428';