这是我第一次在 MySQL 中处理游标和过程。我已经按照MySQL 文档中关于 cursors和roseindia.net的示例进行操作,现在遇到错误:
列计数与第 1 行的值计数不匹配
以下是所涉及的表(这些表尚未标准化为 3NF,因为我收到它们时是这样,是的,我确实意识到我需要使用 Artists.id 而不是 Artists.name):
CREATE TABLE `user_artists_rankings` (
`user_id` varchar(50) NOT NULL DEFAULT '' COMMENT 'kpop_users.user_id',
`artist_name` varchar(100) NOT NULL,
`calculated_score` int(11) DEFAULT NULL,
`last_calculated_score_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`,`artist_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `kpop_users` (
`user_id` char(50) NOT NULL,
`username` char(150) DEFAULT '',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`) USING BTREE,
KEY `name_idx` (`username`),
KEY `twitter_id_idx` (`twitter_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
CREATE TABLE `artists` (
`name` varchar(100) NOT NULL,
`type` varchar(45) DEFAULT NULL,
`official_twitter_screenname` varchar(45) DEFAULT NULL,
`thumbnail_url` varchar(500) DEFAULT NULL,
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `Index_2` (`official_twitter_screenname`)
) ENGINE=InnoDB AUTO_INCREMENT=164 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
目标是在表 user_artists_rankings 中有 user-artist(n) 行,即:
user1 | artist1
user1 | artist2
user1 | artist3
user2 | artist1
user2 | artist2
user2 | artist3
这是我创建的程序:
delimiter ;
drop procedure if exists testrun;
delimiter //
create procedure testrun()
begin
declare d int default 0;
declare user_id varchar(50);
declare artist_name varchar(100);
declare cur_users cursor for select user_id from kpop_users;
declare cur_artists cursor for select name from artists;
declare continue handler for sqlstate '02000' set d=1;
declare continue handler for sqlstate '23000' set d=1;
open cur_users;
open cur_artists;
lbl1: loop
if d=1 then
leave lbl1;
end if;
if not d=1 then
fetch cur_users into user_id;
lbl2: loop
if d=1 then
leave lbl2;
end if;
if not d=1 then
fetch cur_artists into artist_name;
insert into user_artists_rankings values (user_id, artist_name);
end if;
end loop lbl2;
end if;
end loop lbl1;
close cur_users;
close cur_artists;
end
//
delimiter ;
call testrun();
任何帮助将不胜感激。谢谢你。