如何在MySQL中创建触发器以仅在不存在时插入新行?
我想要的是仅当该日期不存在时才插入新行,则应将其忽略。该表没有主键和唯一键,我在此表中使用它bar_opening_details。 我无法在此处添加这样的主要和唯一约束。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
what I want is to insert a new row only if it does not exist on that date then it should be ignored. this table does not have the primary and unique key I am using it in this table bar_opening_details.
I can't add such primary and unique constraints here.to INSERT IGNORE.
since this daily wise entry of items with the same 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就这样解决了
Solved it by this