mysql中的游标更新查询有什么问题?

0ve6wy6x  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(312)

我有一个表,它有一个列顺序\u id,类型int,它们是从1到30的30个数字,并且是唯一的。
我想在mysql中通过查询随机更新这个列,但它们必须是唯一的,并且在1到30之间。我试过这个,但它有问题是“phpmyadmin”在服务器上,并没有显示问题!有人知道问题出在哪里吗?

declare Qid2 int;
declare counter int;
DECLARE done INT DEFAULT FALSE;

declare c cursor
set c = cursor for select order_id from Table_1
open c;
fetch next from c into Qid2;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
while !done DO

  set Qid2 = (select RAND()*30);
  set counter = ( select count(*) from Table_1 where order_id = Qid2);
  while counter!=0 do
    Begin
      set Qid2 = (select RAND()*30);
       set counter =( select count(*) from Table_1 where order_id = Qid2);
    End while;
  update Table_1
  set order_id = Qid2  where current of c;
  fetch next from c ;

End while;
close c;
vnjpjtjt

vnjpjtjt1#

不需要接近逻辑,我就可以识别出6个错误(如果没有设置分隔符,可能是7个)。我纠正了明显的错误。

drop procedure if exists p;
delimiter $$
create procedure p()
begin 
declare Qid2 int;
declare counter int;
declare order_id int; #error 3 not declared
DECLARE done INT DEFAULT FALSE;

declare c cursor for select order_id from Table_1; #error 1 incorrect syntax
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; #error 2 wrong position in code

open c;
fetch next from c into Qid2;

while !done DO

  set order_id = (select RAND()*30); #error 3 not declared
  set counter = ( select count(*) from Table_1 where order_id = Qid2);
  while counter!=0 do
    #Begin      #error 4 not required
      set Qid2 = (select RAND()*30);
       set counter =( select count(*) from Table_1 where order_id = Qid2);
    End while;
  #update Table_1
  # set order_id = Qid2  where current of c; #error 5 where? commented out
  fetch next from c into Qid2 ; #error 6 into missing.

End while;
close c;

end $$
delimiter ;
qncylg1j

qncylg1j2#

DROP TABLE my_table;

CREATE TABLE my_table (i INT NOT NULL);

INSERT INTO my_table VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9);

 SELECT * 
   FROM
      ( SELECT i 
             , @x:=@x+1 x 
          FROM 
             ( SELECT i FROM my_table ORDER BY RAND())a, (SELECT @x:=0) vars
       ) n
   ORDER 
      BY i;
+---+------+
| i | x    |
+---+------+
| 1 |    7 |
| 2 |    2 |
| 3 |    4 |
| 4 |    9 |
| 5 |    3 |
| 6 |    8 |
| 7 |    1 |
| 8 |    6 |
| 9 |    5 |
+---+------+

相关问题