|
楼主 |
发表于 2004-3-15 10:52:40
|
显示全部楼层
这两天查找了 www.mysql.com 上面的资料,
总算想到了解决的方法。
在mysql5.0 上可行,用了存储过程
下面是我的做法,如果有更方便的请告诉我,谢谢!
>
mysql> select * from w; // 分水前
+------+-------+
| id | water |
+------+-------+
| 1 | 5 |
| 2 | 2 |
| 3 | 6 |
| 4 | 6 |
| 5 | 6 |
| 6 | 6 |
| 7 | 6 |
+------+-------+
7 rows in set (0.01 sec)
mysql> delimiter |
mysql> CREATE PROCEDURE fs (IN in_v INT)
-> BEGIN
-> DECLARE done INT DEFAULT 0;
->
-> DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
-> DECLARE cur1 CURSOR FOR SELECT id,water FROM tmp.w;
->
-> DECLARE a CHAR(16);
-> DECLARE v,b,c,d INT;
-> set v=in_v;
-> set d = 0;
-> OPEN cur1;
->
-> REPEAT
-> FETCH cur1 INTO a, b;
->
-> IF NOT done THEN
-> IF v < b THEN
-> set c = b - v;
-> UPDATE tmp.w SET water=c WHERE id=a;
-> set v = 0;
-> set d=d+1;
-> set done =1;
-> ELSE
-> UPDATE tmp.w SET water=0 WHERE id=a; // 例句1
-> set v = v - b;
-> set d=d+1;
-> END IF;
-> END IF;
-> UNTIL done END REPEAT;
->
-> // 本来想把 例句1 写在这里,变成:UPDATE tmp.w SET water=0 WHERE id in (1,2,...);
-> // 但是因为刚学SQL 不知道怎样把 (1,2,...) 付给变量,所以就放弃了。
-> // 望高人指点指点!如何写:变量A = (1,4,2,6,)
-> set @ii = c;
-> set @jj = d;
-> CLOSE cur1;
-> END;|
Query OK, 0 rows affected (0.01 sec)
mysql> call fs(12);| // 开始分水,共有12升
Query OK, 0 rows affected (0.00 sec)
mysql> select * from w;| // 分水后
+------+-------+
| id | water |
+------+-------+
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 6 |
| 5 | 6 |
| 6 | 6 |
| 7 | 6 |
+------+-------+
7 rows in set (0.00 sec)
mysql> select @ii;|
+------+
| @ii |
+------+
| 1 |
+------+
1 row in set (0.00 sec) //最后一个分得水 1升
mysql> select @jj;|
+------+
| @jj |
+------+
| 3 |
+------+
1 row in set (0.00 sec) // 共有3个人分得水 |
|