0
SELECT b.post_title
     , a.post_id
     , Deriv1.Count
FROM  wp_posts b
    , wp_postmeta a
LEFT OUTER JOIN (    
   SELECT meta_value, COUNT( * ) AS Count
   FROM  wp_postmeta
   GROUP BY meta_value
   ) Deriv1 
ON a.post_id = Deriv1.meta_value
WHERE a.meta_value = 1
  AND a.meta_key = 'type-select' 
  AND b.post_status = 'publish'
  and post_type = 'car-cc'

当前的问题SQl STATEMENT是,当我提供meta_value =1它时,它正在获取所有值,即还列出post_id了没有的值。meta_value =1

http://sqlfiddle.com/#!2/1115a7/1

4

1 回答 1

2

我认为问题在于您没有加入 wp_posts 表和 wp_postmeta 表。将此添加到您的 WHERE 子句中:

AND a.post_id = b.ID

或者,只需在两个表上执行 INNER JOIN:

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

顺便说一句——你想要每个组的计数吗?如果是这样,您的查询可以简化:

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

这是一些更新的小提琴。不确定您想要的输出。

祝你好运。

于 2013-01-26T05:51:42.607 回答