2011-06-24 54 views
0

我有我保持一个表保存职位comment_type,我要选择具有重复发表评论型职位数量等MySQL的计数不同的查询

PostExtras 
- id 
- amount 
- post_id (foreign key) 
- comment_type (foreign key) 
- ... 

comment_type 
- id 
- name 

实施例:

- id  - amount - post_id - comment_type 
1   20   23   1 
2   45   23   2 
3   80   28   1 
4   78   28   2 
5   56   23   1 

行1和5实际上是相同的。

+0

复制在什么基础? –

+0

所以,你的意思是相反的不同? –

+0

我的意思是有两个或更多相同的comment_type的职位。 – gandil

回答

0
SELECT post_id FROM PostExtras 
GROUP BY post_id, comment_type 
HAVING COUNT(comment_type) > 1 
+0

id是自动递增的。它除了索引之外没有任何意义。 – gandil

+0

是的。误读和更新。 – ChrisBint

1

如果我的理解是正确的,使用COUNT, GROUP BY and HAVING

SELECT *, COUNT(*) AS itemcount FROM PostExtras 
GROUP BY post_id, comment_type 
HAVING itemcount >= 2 
+0

由于没有将所有字段添加到分组中,因此这不起作用。除了post_id,comment_type之外,您也无法分组,因为每个其他列似乎都有不同的值,然后它们会返回不正确的数据。 – ChrisBint

+0

我已经为post_id添加了WHERE子句,但关于您的其他问题 - 您不必将所有字段添加到MySQL中的GROUP BY子句。 – cypher

+0

尽管目前我无法确认,但您可以添加其他字段而不对其进行分组,这似乎很奇怪。另外添加where子句(表示选择单个行)几乎肯定会破坏这一点。 – ChrisBint