Mysql group by和counts中的Where子句

Mysql group by和counts中的Where子句,mysql,Mysql,在下面的查询中,cnt的值仅根据所选的行数计算。其中id

在下面的查询中,cnt的值仅根据所选的行数计算。其中id<10

我希望它对整个表进行计数,并根据整个表的计数只插入该表的前10行

因此,如果约翰·史密斯(John Smith San Diego California)出现在第11行和第55行,则需要在计数时将其考虑在内

我尝试移动WHERE子句,但这会产生错误

INSERT INTO matchNewCounts(`uniqueidentifier`, `fullName`, `first`, 
`middle`, `last`, `counter`, `city`, `state`, `cit2`, `state2` , `cnt`)
SELECT `uniqueidentifier`, `fullName`, `first`, `middle`, `last`, 
`counter`,`city`, `state`, `cit2`, `state2`, COUNT(*) as cnt 
FROM matchNewIndex
where id < 10 
GROUP BY `first`, `last`, `city`, `state`
样本: 行<10

约翰·史密斯加州圣地亚哥

约翰·史密斯加州圣地亚哥

行>10

约翰·史密斯加州圣地亚哥


预期结果计数必须为3

您应该使用LIMIT而不是WHERE

INSERT INTO matchNewCounts(`uniqueidentifier`, `fullName`, `first`, 
    `middle`, `last`, `counter`, `city`, `state`, `cit2`, `state2` , `cnt`)
SELECT `uniqueidentifier`, `fullName`, `first`, `middle`, `last`, 
    `counter`,`city`, `state`, `cit2`, `state2`, COUNT(*) as cnt 
FROM matchNewIndex
GROUP BY `first`, `last`, `city`, `state`
LIMIT 10

因为,您只需要基于id的前10行。您的查询应该有HAVING子句。因此,如果名称不在序列顺序中,则结果将基于nameorder而不是id生成

INSERT INTO matchNewCounts(`uniqueidentifier`, `fullName`, `first`, 
    `middle`, `last`, `counter`, `city`, `state`, `cit2`, `state2` , `cnt`)
SELECT `uniqueidentifier`, `fullName`, `first`, `middle`, `last`, 
    `counter`,`city`, `state`, `cit2`, `state2`, COUNT(*) as cnt 
FROM matchNewIndex
GROUP BY `first`, `last`, `city`, `state`
HAVING id<10;

您的GROUP BY查询无效,因为您只包含4列,但选择的列多于这4列。一些示例数据可能有助于您在此处获得答案。您是否尝试过限制而不是WHERE??更新您的问题并添加清晰的数据示例和预期结果。@TimBiegeleisen当我在此处运行时,它会执行。@AlexYeskov我的车有时仍然可以在爆胎的情况下驾驶,但这并不意味着司机不应该担心他的车的状况。即使您的查询运行,也没有任何意义。在MySQL中只研究完整的分组模式,以了解更多关于您的问题以及如何解决问题的信息。