gpt4 book ai didi

mysql更新语句执行太慢

转载 作者:行者123 更新时间:2023-12-01 00:52:48 24 4
gpt4 key购买 nike

我的问题中有如下两个表。

CREATE TABLE `t_user_relation` (
`User_id` INT(32) UNSIGNED NOT NULL ,
`Follow_id` INT(32) UNSIGNED NOT NULL ,
PRIMARY KEY (`User_id`,Follow_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `t_user_info`(
`User_id` int(32) unsigned NOT NULL ,
`User_name` varchar(20) NOT NULL ,
`User_avatar` varchar(60) NOT NULL ,
`Msg_count` int(32) unsigned DEFAULT '0' ,
`Fans_count` int(32) unsigned DEFAULT '0' ,
`Follow_count` int(32) unsigned DEFAULT '0' ,
PRIMARY KEY (`User_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

我想做的是更新 t_user_info 表的 Fans_count 字段。我的更新声明如下:

 UPDATE t_user_info set t_user_info.Fans_count=(SELECT COUNT(*) FROM t_user_relation
WHERE t_user_relation.Follow_id=t_user_info.User_id);

但是执行起来真的很慢! t_user_info表包含20,445条记录,t_user_relation表包含1,809,915条记录。谁能帮我提高速度!感谢您的任何建议!

最佳答案

我会试试这个:

UPDATE
t_user_info inner join
(SELECT Follow_id, COUNT(*) as cnt
FROM t_user_relation
GROUP BY Follow_id) s
on t_user_info.User_id=s.Follow_id
SET t_user_info.Fans_count=s.cnt

我正在使用子查询计算表 t_user_relation 中每个 Follow_id 的行数:

SELECT Follow_id, COUNT(*) as cnt
FROM t_user_relation
GROUP BY Follow_id

然后我将此查询的结果与 t_user_info 连接起来,并在连接成功的地方更新 Fans_count,将其设置为在子查询中计算的计数。

这样编写的查询通常运行得更快,因为子查询的结果行在连接之前只计算一次,而在您的解决方案中,您的子查询为每个用户行计算一次。

关于mysql更新语句执行太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13890425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com