phpmyadmin 如何在MySQL中创建一个触发器,以便仅在不存在新行时插入新行?

vuv7lop3  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(157)

我想要的是插入一个新行,如果该行在该日期不存在,则应忽略该行。此表没有主关键字和唯一关键字。我在此表中使用它bar_opening_details。我无法添加此类主约束和唯一约束here.toINSERT 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
kse8i1jr

kse8i1jr1#

用这个解决了

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

相关问题