0

可能重复:
我可以一起使用 COUNT() 和 DISTINCT 吗?

我有这个 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”。

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

4

3 回答 3

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 的计数。

于 2012-10-12T09:14:16.450 回答
0

由于第一个查询显示 2 行,因此第二个查询应该返回2,并且确实如此。这是正常工作的。

于 2012-10-12T09:12:48.880 回答
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')
于 2012-10-12T09:27:00.123 回答