0

我想做这样的事情:

CREATE TRIGGER addwinner AFTER INSERT ON bids
FOR EACH ROW BEGIN 
IF exists(select * from wins as LT where LT.item_index=NEW.item_index) THEN

SELECT item_index, MIN( bid_amount ) 
FROM update_winnerslist AS a1
WHERE a1.item_index =  NEW.item_index;
UPDATE wins SET email_id=NEW.emai_id, bid_amount=a1.bid_amount where wins.item_index=a1.item_index;

END IF;
END;

基本上我想要的是通过比较某些属性来使用另一个表的元组更新一个表。

4

1 回答 1

0

手册中所述,在定义过程/触发器/等时。在它们的主体中使用;来分隔命令,您需要定义一个备用分隔符,以便将CREATE命令解释为单个语句。

UPDATE使用 的结果SELECT,就像您描述的那样,您可以执行以下任何操作:

  1. 将 的结果保存SELECT在一个变量中,然后在UPDATE:

    DELIMITER ;; -- or anything else you like
    
    CREATE TRIGGER addwinner AFTER INSERT ON bids FOR EACH ROW
      IF EXISTS (SELECT * FROM wins AS LT WHERE LT.item_index=NEW.item_index)
      THEN
        SELECT MIN(bid_amount) INTO @bid_amount
        FROM   update_winnerslist AS a1
        WHERE  a1.item_index = NEW.item_index;
    
        UPDATE wins
        SET    email_id=NEW.emai_id, bid_amount=@bid_amount
        WHERE  wins.item_index=a1.item_index;
      END IF;;  -- whatever command delimiter you chose above goes here
    
    DELIMITER ; -- reset to normal
    
  2. 只需使用子查询(只要它不引用您正在更新的表):

    DELIMITER ;; -- or anything else you like
    
    CREATE TRIGGER addwinner AFTER INSERT ON bids FOR EACH ROW
      IF EXISTS (SELECT * FROM wins AS LT WHERE LT.item_index=NEW.item_index)
      THEN
        UPDATE wins
        SET    wins.email_id=NEW.emai_id, wins.bid_amount=(
          SELECT MIN(bid_amount)
          FROM update_winnerslist AS a1
          WHERE a1.item_index = NEW.item_index
        )
        WHERE  item_index = NEW.item_index
      END IF;;  -- whatever command delimiter you chose above goes here
    
    DELIMITER ; -- reset to normal
    
  3. 或者只是加入表格:

    DELIMITER ;; -- or anything else you like
    
    CREATE TRIGGER addwinner AFTER INSERT ON bids FOR EACH ROW
      IF EXISTS (SELECT * FROM wins AS LT WHERE LT.item_index=NEW.item_index)
      THEN
        UPDATE wins JOIN update_winnerslist AS a1 USING (item_index)
        SET    wins.email_id=NEW.emai_id, wins.bid_amount=MIN(a1.bid_amount);
        WHERE  item_index = NEW.item_index
      END IF;;  -- whatever command delimiter you chose above goes here
    
    DELIMITER ; -- reset to normal
    
于 2012-04-25T21:54:27.617 回答