Mysql

在 mysql 過程中的查詢內部循環。可能嗎?

  • January 12, 2017

我有以下查詢:

INSERT INTO major (key_1, key_2, ... , key_N) 
VALUES (v_1_1, v_1_2, v_1_3, ... , c_1_N)
      (v_2_1, v_2_2, v_2_3, ... , c_2_N)
      ...
      (v_K_1, v_K_2, v_K_3, ... , c_K_N)

其中key_i是列的名稱,並且是從到v_i_j的隨機值。,並且是正整數(我們的輸入)。1``L``N``L``K

我將編寫mysql 程序來創建隨機(值從1to L)矩陣*(Kx N)並使用上面提供的查詢將其放置到數據庫中。


現在它是通過程式碼實現的phpdoctrine但我想在純 SQL 過程中實現與輸入相同的結果(N,,,LK。有php程式碼:

$conn = DriverManager::getConnection($connectionParams);
$conn->beginTransaction();
try {
   for ($i = 1; $i <= $k; $i++) {     // row in table major
       $content=[];
       for ($j = 1; $j <= $n; $j++) {   // foreign key of row
           $content['key_' . $j] = rand(1, $l);
       }
       $conn->insert('major', $content);
   }
   $conn->commit();
} catch(\Exception $e) {
   $conn->rollBack();
   throw $e;
}

*我寫過matrices,但我知道沒有行的順序,它不是嚴格意義上的矩陣。


所以我不想在循環內進行查詢,而是在查詢內循環。我知道這是不好的做法,但我正在考慮在過程中連接和評估查詢?有可能的?還是這些更好的解決方案?

我通過以下程式碼解決了這個問題:

drop procedure if exists populate;
delimiter $$
CREATE PROCEDURE populate (IN n INT, IN l INT, IN k INT)
BEGIN
 declare _k int unsigned DEFAULT 0;
 declare _n int unsigned DEFAULT 0;
 declare _l int unsigned DEFAULT 0;
 DECLARE _stmt TEXT DEFAULT 'INSERT INTO major_1 (';

 WHILE _n < n DO set _n=_n+1;
   set _stmt = CONCAT(_stmt,'minor_',_n,'_id');
   IF _n<n THEN set _stmt = CONCAT(_stmt,','); END IF;
 END WHILE;
 set _stmt = CONCAT(_stmt,') VALUES ');

 while _k < k do set _k=_k+1;
   set _stmt = CONCAT(_stmt,'(');
   set _n=0; WHILE _n < n do set _n=_n+1;
     SET _stmt = CONCAT(_stmt,CEIL(RAND()*l));
     IF _n<n THEN set _stmt = CONCAT(_stmt,','); END IF;
   END WHILE;
   IF _k<k THEN set _stmt = CONCAT(_stmt,'),');
   ELSE set _stmt = CONCAT(_stmt,');'); END IF;
 end while;

# code to debug:
# SELECT n,l,k,_stmt;

 SET @STMT = _stmt;
 PREPARE stmt FROM @stmt;
 EXECUTE stmt;
 DEALLOCATE PREPARE stmt;
END $$
delimiter ;

這可以通過命令使用(對於 N=20,L=25,K=3):

CALL populate(20,25,3);

資料來源:

MySQL 中的循環

https://stackoverflow.com/questions/1485668/how-to-set-initial-value-and-auto-increment-in-mysql

執行文本變數作為查詢

https://stackoverflow.com/questions/190776/how-to-have-dynamic-sql-in-mysql-stored-procedure

引用自:https://dba.stackexchange.com/questions/160805