MySql 工作台 - 游标

标签 mysql mysql-workbench

为什么我不能这样做?我想从 TABLEA 中搜索大于光标值的最接近的值,对两者执行平均函数并将结果放入 test3 中。我收到错误代码 1054 未知列“Xnearest in 'field list'”。以下代码来 self 的程序:

    BEGIN
     #THIS DOES NOT WORK Unknown column Xnearest in field list, error, 
      # declare local variables
     Declare done boolean default 0; 
     Declare xval double; 
     declare i integer default 1;
     Declare Xnearest double;
     Declare polypoint double;

     #declare the cursor
     Declare rows cursor for Select x from TABLE_A;
     #declare continue handler
    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1; #SQL state look through table until no more rows
     # create a table for results if non exists
     CREATE TABLE IF Not Exists test3  (Row_no integer, x_val double, X_Nearest double, x_greater double);
     #OPEN THE CURSOR
     OPEN rows;
     # tell it to loop through all rows
     repeat
     #get x value
     FETCH rows into xval;

    SET Xnearest = (select x from TABLEA where x>xval order by x asc limit 1);
    Set polypoint = xval+abs(xval-Xnearest)/2;

     Insert into test3 (Row_no, x_val,Xnearest,polypoint) Values (i,xval,X_Nearest,x_greater);
     set i=i+1; 


      UNTIL done END REPEAT;
     #close the cursor
     CLOSE rows;
     End

最佳答案

语法略有混淆,代码现在可以工作了!

    BEGIN
    #example cursor attempt to travel through each row at a time, but this time while performing a function and putting result in a new table
     # declare local variables
     Declare done boolean default 0; 
     Declare xval double; 
     declare i integer default 1;
     Declare Xnearest double;
     Declare polypoint double;

     #declare the cursor
     Declare rows cursor for Select x from TABLEA;
     #declare continue handler
     DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1; #SQL state is an error code, so look through table until no more rows, which applied for this error code
    # create a table for results if non exists
     CREATE TABLE IF Not Exists test3  (Row_no integer, x_val double, X_Nearest double, x_greater double);
    #OPEN THE CURSOR
     OPEN rows;
     # tell it to loop through all rows
     repeat
     #get x value
     FETCH rows into xval;

    SET Xnearest = (select x from TABLEA where x>xval order by x asc limit 1);
    Set polypoint = xval+abs(xval-Xnearest)/2;

     Insert into test3 (Row_no, x_val, X_nearest, x_greater) Values (i,xval,Xnearest,polypoint);
     set i=i+1; 


     UNTIL done END REPEAT;
     #close the cursor
     CLOSE rows;
    End

关于MySql 工作台 - 游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59258821/

相关文章:

mysql workbench记录限制

php - 不能特别插入到一张表中

mysql - 如何选择所有行 (*) 加上我选择的一些额外行

从 MS SQL-Server 迁移数据库时 MYSQL Workbench "Incorrect string value"错误

mysql - 如何在 SQL 上创建多值属性

mysql - 不同表使用相同的字段名进行联合查询有问题吗?

mysql - 如何用一条 SQL 语句 upsert 两个数据库表?

mysql - 使用 MySQL 与 NoSQL 的单个服务器上的 Key-Value 数据库是否存在高性能差异

c# - 如何在不使用 DataReader 的情况下找到我的 product_id?

mysql - 身份验证插件 'caching_sha2_password'无法加载