Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL计数不同查询_Mysql_Select_Distinct Values - Fatal编程技术网

MySQL计数不同查询

MySQL计数不同查询,mysql,select,distinct-values,Mysql,Select,Distinct Values,我有一张表,上面有我的评论、类型、金额等 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

我有一张表,上面有我的评论、类型、金额等

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行实际上是相同的。

如果我理解正确,请使用

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

那么你的意思是与distinct相反?我的意思是有两个或更多相同注释类型的帖子是自动递增的。除索引外,它没有其他含义。由于未将所有字段添加到分组中,因此这将不起作用。除了post_id、comment_type之外,您也不能按任何内容进行分组,因为其他每一列的值似乎不同,这将返回不正确的数据。我为post_id添加了WHERE子句,但是关于你的另一个担忧——你不必在MySQL中将所有字段都添加到GROUPBY子句中。虽然我现在无法确认,但是你可以添加额外的字段而不进行分组,这似乎很奇怪。此外,添加where子句(表示选择了一行)几乎肯定会打破这一局面。基于上述数据,删除where子句将导致返回两行,这是我从上述查询中所期望的,但并不正确。将SQL修改为;选择,COUNT()作为PostExtras组中的itemcount(按post\u id,注释类型,itemcount>=2);会有用的。但是,您仍然返回不必要的信息,因为所需的只是post_id。是的,这是不正确的,我可能误解了问题,并且更新了答案。然而,他想选择“评论类型重复的帖子”,而不仅仅是帖子ID。
SELECT *, COUNT(*) AS itemcount FROM PostExtras 
GROUP BY post_id, comment_type
HAVING itemcount >= 2