嵌套而不能按预期工作

时间:2013-08-03 14:04:39

标签: mysql

我有两张桌子。一张桌子是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表中找到了另一个俱乐部,则他/她在{{1}中被标记为fail } the_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

我该如何纠正?

1 个答案:

答案 0 :(得分: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);

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