使用子句编写使用另一个表的属性更新表的查询

时间:2012-04-25 21:36:55

标签: mysql

我想做这样的事情:

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;

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

1 个答案:

答案 0 :(得分:0)

正如in the manual所解释的那样,在定义过程/触发器/等时。在其正文中使用;来分隔命令,您需要定义一个备用分隔符,以便将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