0

我有两张桌子。一张是the_temp http://sqlfiddle.com/#!2/dbbae/1,另一张是members http://sqlfiddle.com/#!2/afaab3/1

members表包含俱乐部的所有成员,并且the_temp只是一个临时表,在将记录添加到成员表之前会在其中查看记录。

规则是成员cannot be in two clubs in the same year

为了解决这个问题,我一次取一条记录,并使用这个存储过程the_temp对表中的每条记录运行它。members

如果在给定的年份temp_table中发现表中的成员在表中的另一个俱乐部中members,则将他/她标记为failthe_temp'the_temp_status列中。

这是存储过程

DELIMITER ;;
CREATE PROCEDURE leshex()
BEGIN

DECLARE n INT DEFAULT 0;
DECLARE x INT DEFAULT 0;

DECLARE the_temp_name VARCHAR(40) DEFAULT 0;
DECLARE lestemp VARCHAR(40) DEFAULT 0;
DECLARE lesmember VARCHAR(40) DEFAULT 0;
DECLARE the_temp_club_id VARCHAR(40) DEFAULT 0;
DECLARE the_temp_membership_year VARCHAR(40) DEFAULT 0;

DECLARE member_name VARCHAR(40) DEFAULT 0;
DECLARE member_club_id VARCHAR(40) DEFAULT 0;
DECLARE membership_year VARCHAR(40) DEFAULT 0;

SELECT COUNT(*) FROM the_temp INTO n;
SELECT COUNT(*) FROM members into x;

SET lesmember=0;
SET lestemp=0;

WHILE lestemp<n DO 
select the_temp_name into the_temp_name from the_temp where the_temp_id=lestemp;
select the_temp_club_id into the_temp_club_id from the_temp where the_temp_id=lestemp;
select the_temp_membership_year into the_temp_membership_year from the_temp where the_temp_id=lestemp;

WHILE lesmember<x DO
select member_name into member_name from members where member_id=lesmember;
select member_club_id into member_club_id from members where member_id=lesmember;
select membership_year into membership_year from members where member_id=lesmember;

IF EXISTS(select member_club_id from members 
where member_club_id in (1,2) AND member_name=the_temp_name AND membership_year=the_temp_membership_year)

THEN

update the_temp SET the_temp_status='fail' where the_temp_name=member_name;

else

update the_temp SET the_temp_status='pass' where the_temp_name=member_name;
END IF;
END WHILE;

END WHILE;
/* 
Finally

insert into (member_name,member_club_id,membership_year) select the_temp_name,the_temp_club_id,the_temp_membership_year from the_temp where the_temp_status='pass';

*/
End;
;;

当我存储过程时,它会将所有记录标记为pass,这是错误的,因为我有一个失败的记录。the_temp存储过程不会停止迭代,我通过

SHOW PROCESSLIST;
KILL n;

我应该如何纠正这个?

4

1 回答 1

1

您想temp.status = 'fail'在同一年有两个会员资格时进行设置。

哇。这是一个update查询,不需要任何显式循环:

update temp left outer join
       (select member_name, member_year, count(*) as cnt
        from members
        group by member_name, member_year
       ) my
       on temp.member_name = my.member_name and
          temp.the_temp_membership_year = my.member_year
  set temp.the_temp_status = (case when cnt is null or cnt = 1 then 'pass' else 'fail' end);

让数据库完成处理数据的工作,使用(主要)连接和聚合。这就是关系数据库的力量。

于 2013-08-03T14:36:01.497 回答