wordpress自定义查询以选择元值

时间:2013-07-24 13:23:06

标签: php mysql wordpress

SELECT b.post_title, a.post_id, COUNT( * ) as Total
FROM  wp_posts b INNER JOIN 
            wp_postmeta a ON a.post_id = b.ID
    WHERE a.meta_value = 1
      AND a.meta_key = 'type-select' 
      AND b.post_status = 'publish'
      and post_type = 'car-cc'
GROUP BY b.post_title, a.post_id

目前它选择了post titlepost id,但我还需要选择meta value其中元键= type-gen 问题是另一个元键是已经在查询中进行了比较。

SQL小提琴:http://sqlfiddle.com/#!2/109c2/1

3 个答案:

答案 0 :(得分:3)

你去吧

SELECT b.post_title, a.post_id, COUNT( * ) AS Total,
(SELECT meta_value FROM  `wp_postmeta` WHERE post_id= b.ID AND meta_key='type-gen') AS 'new  meta value'
FROM  wp_posts b INNER JOIN 
            wp_postmeta a ON a.post_id = b.ID
    WHERE a.meta_value = 1
      AND a.meta_key = 'type-select' 
      AND b.post_status = 'publish'
      AND post_type = 'car-cc'
GROUP BY b.post_title, a.post_id

Fiddle

答案 1 :(得分:1)

SELECT b.post_title, a.post_id, COUNT( * ) as Total
FROM  wp_posts b INNER JOIN 
            wp_postmeta a ON a.post_id = b.ID
    WHERE (a.meta_value = 1
      AND a.meta_key = 'type-select' 
      AND b.post_status = 'publish'
      and post_type = 'car-cc') 
    OR (a.meta_value = 1
      AND a.meta_key = 'type-gen' 
      AND b.post_status = 'publish'
      and post_type = 'car-cc')
GROUP BY b.post_title, a.post_id

答案 2 :(得分:1)

使用WP_Query

Codex page

修改
$args = array(
  'post_type' => 'car-cc',
  'meta_query' => array(
    array(
      'key' => 'type-select',
      'value' => '1',
      'compare' => '='
),
    array(
      'key' => 'type-gen',
      'value' => 'my-great-type',
      'compare' => 'LIKE'
    )
  )
);

$query = new WP_Query( $args );