MYSQL选择多行

时间:2018-04-13 22:53:54

标签: mysql triggers

我有这个触发器,它检查已结束拍卖的名为拍卖的表。拍卖结束后,将一名获胜者列入该栏目。然后触发器检查是否有有效的赢家。问题是当它检查拍卖标签时,一个人赢得了2个或更多的出价。它表示结果行有多个列,这是有道理的,因为该人赢得了2行或更多行。我的问题是如何使用SELECT INTO插入具有相同“赢家”的多行。

DELIMITER;

 DELIMITER $$
CREATE TRIGGER notify_winner
    AFTER UPDATE ON Auctions
    FOR EACH ROW 
BEGIN

    SELECT A.winner, A.vin INTO @buyer, @vin
    FROM Auctions AS A WHERE A.winner != 'NONE' AND A.winner IS NOT NULL;

    INSERT INTO Wins (winner,vin)
    values (@buyer, @vin);



END$$
DELIMITER ;

1 个答案:

答案 0 :(得分:0)

实际上你不能。当只有一行时,使用Select Into。改用光标。例如:

DELIMITER $$
CREATE TRIGGER notify_winner
  AFTER UPDATE ON Auctions
  FOR EACH ROW 

BEGIN
  DECLARE done INT DEFAULT FALSE;

  DECLARE cur1 CURSOR FOR 
  SELECT A.winner, A.vin 
    FROM Auctions AS A 
   WHERE A.winner != 'NONE' 
     AND A.winner IS NOT NULL;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO @buyer, @vin;

    IF done THEN
      LEAVE read_loop;
    END IF;

    INSERT 
      INTO Wins (winner,vin)
    values (@buyer, @vin);

  END LOOP;

  CLOSE cur1;

END$$
DELIMITER ;

有关详细信息,请查看以下链接:https://dev.mysql.com/doc/refman/5.7/en/cursors.html

希望它有所帮助!