分组依据和计数中的where子句

时间:2019-05-19 09:22:47

标签: mysql

在下面的查询中,cnt的值仅基于所选的行数来计算。 (ID <10)

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

因此,如果约翰·史密斯(加利福尼亚州圣地亚哥的圣地亚哥)出现在第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

John Smith加利福尼亚圣地亚哥圣地亚哥

John Smith加利福尼亚圣地亚哥圣地亚哥

行> 10

John Smith加利福尼亚圣地亚哥圣地亚哥

预期结果的计数必须为3。

2 个答案:

答案 0 :(得分:0)

您应该使用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

答案 1 :(得分:0)

自此,您仅需要基于id的前10行。您的查询应包含HAVING子句。因此,如果names的顺序不正确,则结果将根据name的顺序而不是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;
相关问题