MySQL:按值计算记录,然后用计数更新另一列
三个非常相关的SQL问题(我实际上使用的是mySQL):
假设一个人员表有两列名称,国家
1)我如何向有同胞的人展示?我可以按国家显示公民人数:
select country, count(*) as fellow_citizens
from people
group by country
但是我似乎无法显示那些与其他人相关的记录> 1.以下内容无效:
select name, country, count(*) as fellow_citizens
from people
group by country
where fellow_citizens > 1;
……因为我不想把人分组,所以不会是我想要的任何方式.
2)为了解决上述问题,我有了将fellow_citizens存储在新列中的想法.这听起来像是MySQL: Count records from one table and then update another等问题的变体.区别在于我想要更新同一个表.
但是那里给出的答案在这里不起作用:
update people as dest
set fellow_citizens =
(select count(*) from people as src where src.country = dest.country);
我收到此错误消息:
You can’t specify target table ‘dest’ for update in FROM clause
看来我需要通过另一个临时表来做到这一点.可以在没有临时表的情况下完成吗?
3)作为上述的变体,如何按国家/地区更新人员列?我发现我可以通过以下方式更新全局计数器:
set @i:=0; update people set counter = @i:=@i+1 order by country;
但是,当国家的价值发生变化时,我想重置我的@i计数器.
有没有办法在mySQL中做到这一点而不需要完整的程序代码?