在我的问题中有两个表。
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条records.Can组成,有谁能帮我提高速度!谢谢你的建议!
发布于 2012-12-15 16:19:42
我会试试这个:
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,将其设置为子查询中计算的计数。
这样编写的查询通常运行得更快,因为子查询的结果行在连接之前只计算一次,而在您的解决方案中,子查询为每个用户行计算一次。
发布于 2012-12-15 16:04:43
在处理数据库中的大量记录时,您希望避免使用通配符(*),而是使用indexes。
https://stackoverflow.com/questions/13890425
复制相似问题