如何在 MySQL 中创建触发器以仅在不存在时插入新行?
how to create an trigger in MySQL to insert new row only if not exists?
我想要的是只有在该日期不存在时才插入一个新行,然后它应该被忽略。这个 table 没有我在这个 table bar_opening_details 中使用的主键和唯一键。
我无法添加这样的主要和唯一约束 here.to INSERT IGNORE。
因为每天明智地输入具有相同 item_id.
的项目
CREATE definer=`root`@`localhost` TRIGGER `store`.`bar_recvd_details_after_insert` beforeINSERT
on `bar_recvd_details` FOR each row BEGIN
DECLARE mydate date;DECLARE mydate1 DATE;DECLARE myid INT;SELECT Max(close_date)
INTO mydate
FROM bar_opening_details;SELECT item_id
INTO myid
FROM bar_opening_details
WHERE op_date=mydate
AND item_id=new.item_id;SELECT op_date
INTO mydate1
FROM bar_opening_details
WHERE op_date=mydate
AND item_id=new.item_id;IF(myid != new.item_id
AND
mydate1 != mydate) then
INSERT INTO `store`.`bar_opening_details`
(
`item_cid`,
`item_id`,
`op_date`,
`op_value`,
`close_date`,
`close_val`
)
VALUES
(
new.item_cid,
new.item_id,
mydate,
'0',
mydate,
'0'
);ENDIF;END
这样解决了
CREATE DEFINER=`root`@`localhost` TRIGGER `store`.`bar_recvd_details_BEFORE_INSERT` BEFORE INSERT ON `bar_recvd_details` FOR EACH ROW
BEGIN
declare mydate date;
SELECT max(close_date) into mydate FROM bar_opening_details;
IF NOT EXISTS (SELECT 1 FROM bar_opening_details WHERE item_id = NEW.item_id and op_date=mydate) THEN
INSERT INTO bar_opening_details (item_cid,
item_id,
op_date,
op_value,
close_date,
close_val)
VALUES (NEW.item_cid,NEW.item_id,mydate,'0',mydate,'0');
END IF;
END
我想要的是只有在该日期不存在时才插入一个新行,然后它应该被忽略。这个 table 没有我在这个 table bar_opening_details 中使用的主键和唯一键。 我无法添加这样的主要和唯一约束 here.to INSERT IGNORE。 因为每天明智地输入具有相同 item_id.
的项目CREATE definer=`root`@`localhost` TRIGGER `store`.`bar_recvd_details_after_insert` beforeINSERT
on `bar_recvd_details` FOR each row BEGIN
DECLARE mydate date;DECLARE mydate1 DATE;DECLARE myid INT;SELECT Max(close_date)
INTO mydate
FROM bar_opening_details;SELECT item_id
INTO myid
FROM bar_opening_details
WHERE op_date=mydate
AND item_id=new.item_id;SELECT op_date
INTO mydate1
FROM bar_opening_details
WHERE op_date=mydate
AND item_id=new.item_id;IF(myid != new.item_id
AND
mydate1 != mydate) then
INSERT INTO `store`.`bar_opening_details`
(
`item_cid`,
`item_id`,
`op_date`,
`op_value`,
`close_date`,
`close_val`
)
VALUES
(
new.item_cid,
new.item_id,
mydate,
'0',
mydate,
'0'
);ENDIF;END
这样解决了
CREATE DEFINER=`root`@`localhost` TRIGGER `store`.`bar_recvd_details_BEFORE_INSERT` BEFORE INSERT ON `bar_recvd_details` FOR EACH ROW
BEGIN
declare mydate date;
SELECT max(close_date) into mydate FROM bar_opening_details;
IF NOT EXISTS (SELECT 1 FROM bar_opening_details WHERE item_id = NEW.item_id and op_date=mydate) THEN
INSERT INTO bar_opening_details (item_cid,
item_id,
op_date,
op_value,
close_date,
close_val)
VALUES (NEW.item_cid,NEW.item_id,mydate,'0',mydate,'0');
END IF;
END