1

Howdy - I'm a MySQL Noob. I have a table of various business listings and I am trying to populate a second table called cities that contains unique city names along with a count of how many listings per city. I'm able to do a SELECT statement that gets me this data fine like so:

SELECT city,state,sum(count)
FROM (
SELECT city,state, 1 AS count FROM listings
) results
GROUP BY city
ORDER BY sum(count) DESC,city;

However, now I want to update the table, but I can't seem to get a proper statement to work. This is the latest that I have, but I'm currently getting a "Invalid use of group function" error.

INSERT INTO cities(city,state,size)
SELECT city,state,sum(count)
FROM (
SELECT city,state, 1 AS count FROM listings
) results
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), size=sum(count); 

Any help is appreciated!

4

2 回答 2

3

像这样简单的事情会起作用吗?

insert into cities (city, state, size)
select city, state, count(*) as size from listings
group by city, state

group by应该确保没有重复,这样就不需要on duplicate key. 你正在做的 sum() + 子查询看起来就像你只是想做一个 count(*)。

您得到的具体错误是由于 size=sum(count)。在批量插入中,正确的方法是 size=values(size),请参阅values().

编辑:

如果它为每个城市添加另一个条目,那么城市上没有唯一索引,并且重复键无论如何都不会做任何事情。

如果您在 (city, state) 上添加唯一索引,那么您可以添加on duplicate key update size=values(size)到上述查询中,它将更新每条记录。

于 2009-11-11T00:39:11.287 回答
0

试试这个,虽然我希望在向你释放它之前我有一些东西可以测试它。

insert into cities (city, state, size)
select city, state, count(*) AS size
from listings
group by city, state
于 2009-11-11T00:40:44.850 回答