计算MySQL查询中的行数

时间:2012-10-12 09:05:32

标签: mysql sql count

  

可能重复:
  COUNT() and DISTINCT can i use together?

我有这个sql语句:

SELECT * FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE ( wp_term_relationships.term_taxonomy_id IN (4,3) )
AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'published')

我得到两行ID相同的>预期

添加GROUP BY wp_posts.ID会将行数减少到一个

现在我想获取带有SQL查询的行数

SELECT COUNT(*) AS cnt FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE ( wp_term_relationships.term_taxonomy_id IN (4,3) )
AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'published')
GROUP BY wp_posts.ID

即使使用“GROUP BY”,我也会得到“2”而不是“1”。

从第一个语句中获取行数的正确语句是什么?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT count(DISTINCT wp_posts.ID) as cnt FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE ( wp_term_relationships.term_taxonomy_id IN (4,3) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'published')

这将为您提供结果行中唯一ID的计数。

答案 1 :(得分:0)

由于第一个查询显示2行,因此第二个查询应返回2,并且它会返回{{1}}。这是应该的。

答案 2 :(得分:0)

拥有那个GROUP BY并没有真正的逻辑意义。

一个简单的解决方法是使用原始sql作为子选择并根据它进行计数: -

SELECT COUNT(*) AS cnt  
FROM (SELECT wp_posts.ID  
FROM wp_posts 
INNER JOIN wp_term_relationships  
ON (wp_posts.ID = wp_term_relationships.object_id) 
WHERE ( wp_term_relationships.term_taxonomy_id IN (4,3) ) 
AND wp_posts.post_type = 'post'  
AND (wp_posts.post_status = 'published') 
GROUP BY wp_posts.ID) Sub1

或者下面的内容可能没问题,具体取决于表之间的关系(以及wp_posts.ID的唯一性)。

SELECT COUNT(DISTINCT wp_posts.ID) 
FROM wp_posts
INNER JOIN wp_term_relationships 
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE ( wp_term_relationships.term_taxonomy_id IN (4,3) )
AND wp_posts.post_type = 'post' 
AND (wp_posts.post_status = 'published')