我有一个下面给出的表结构。
Name
必须自动生成包含CREATE TABLE `sample` (
`PK_ID` varchar(10) NOT NULL,
`RQ_ID` varchar(10) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`BID_VAL` double NOT NULL DEFAULT '0',
`max_bid` double NOT NULL,
`Last_updated` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
max_bid
我需要一个触发器,它会在max(BID_VAL) group by RQ_ID
max_bid
谢谢。
答案 0 :(得分:2)
您不能在导致触发器的同一个表中进行更新或插入,但您可以这样做: 更新记录的max_bid,因为你插入它
DELIMITER ||
CREATE TRIGGER `calculate_max_bid` BEFORE insert ON `sample` FOR EACH ROW
begin
DECLARE max_bid_val double;
SELECT
max(BID_VAL) into max_bid_val
FROM sample
WHERE
RQ_ID = new.RQ_ID
GROUP BY RQ_ID;
if max_bid_val > new.bid_val then
SET new.max_bid = max_bid_val;
ELSE
SET new.max_bid = new.BID_VAL;
end if;
END ||
DELIMITER ;
答案 1 :(得分:1)
你可以像这样使用程序:
DELIMITER ||
CREATE PROCEDURE update_max (
IN PK_ID_val varchar(10),
IN RQ_ID_VAL varchar(10) ,
IN BID_VAL_VAL double ,
IN Last_updated_VAL datetime
)
BEGIN
DECLARE calcul_max_bid double;
insert into sample
(PK_ID,RQ_ID,BID_VAL,MAX_BID,Last_updated)
values (PK_ID_VAL,RQ_ID_VAL,BID_VAL_VAL,0,Last_updated_VAL);
SELECT
max(BID_VAL) into calcul_max_bid
FROM sample
WHERE
RQ_ID = RQ_ID_VAL
GROUP BY RQ_ID;
update sample set max_bid = calcul_max_bid where RQ_ID=RQ_ID_val;
END ||
DELIMITER ;
所以代替执行insert直接调用此过程
call update_max('A','RQ_1',12.0,'2016-12-12');