MySQL加入了查询计数,为每个结果返回一行

时间:2012-07-17 13:08:54

标签: mysql sql wordpress group-by left-join

所以,我正在做一个自定义wordpress查询来拉取事件(事件存储在自定义字段(元数据)中因此需要JOIN)并且我想得到返回行的计数。我的问题是我收到了一堆行,每行都包含针对每个帖子ID的计数。

我的查询看起来有点像这样:

SELECT count(*)
FROM   wp_posts AS wposts 
   LEFT JOIN wp_postmeta AS metafeatured 
          ON wposts.id = metafeatured.post_id 
   LEFT JOIN wp_postmeta AS metastart 
          ON wposts.id = metastart.post_id 
   LEFT JOIN wp_postmeta AS metaend 
          ON wposts.id = metaend.post_id 
   LEFT JOIN wp_term_relationships 
          ON ( wposts.id = wp_term_relationships.object_id ) 
   LEFT JOIN wp_term_taxonomy 
          ON ( wp_term_relationships.term_taxonomy_id = 
               wp_term_taxonomy.term_taxonomy_id ) 
WHERE  wposts.post_type = 'll_events' 
   AND wposts.post_status = 'publish' 
   AND ( ( ( metastart.meta_key = 'll_events_startdate' 
             AND Cast(metastart.meta_value AS UNSIGNED) < 1342997940 ) 
           AND ( metaend.meta_key = 'll_events_enddate' 
                 AND Cast(metaend.meta_value AS UNSIGNED) > 1342525664 ) ) 
          OR ( ( metastart.meta_key = 'll_events_startdate' 
                 AND Cast(metastart.meta_value AS UNSIGNED) <= 1342997940 ) 
               AND ( metaend.meta_key = 'll_events_enddate' 
                     AND Cast(metaend.meta_value AS UNSIGNED) >= 1342525664 
                   ) ) 
          OR ( ( metastart.meta_key = 'll_events_startdate' 
                 AND Cast(metastart.meta_value AS UNSIGNED) BETWEEN 
                     1342525664 AND 1342997940 
                   ) 
               AND ( metastart.meta_key = 'll_events_enddate' 
                     AND Cast(metaend.meta_value AS UNSIGNED) BETWEEN 
                         1342525664 AND 1342997940 
                   ) ) 
          OR ( ( metastart.meta_key = 'll_events_startdate' 
                 AND Cast(metastart.meta_value AS UNSIGNED) BETWEEN 
                     1342525664 AND 1342997940 
                   ) 
               AND ( metaend.meta_key = 'll_events_enddate' 
                     AND Cast(metaend.meta_value AS UNSIGNED) <= 1 ) ) ) 
GROUP BY wposts.ID, metastart.post_id, metaend.post_id, wp_term_relationships.object_id
ORDER BY metastart.meta_value ASC 

我已经尝试了大量的群组,计数等组合,并且无法获得预期的结果(结果集中的一行包含&#39; count&#39;)。相反,我的结果集看起来像:

count(*)
24
30
30
30
12
16
1

......依此类推,我需要的地方:

count(*)
139

1 个答案:

答案 0 :(得分:1)

只需删除GROUP BY子句

即可