如果不存在唯一列,MySQL将插入多条记录

时间:2014-03-17 20:57:04

标签: php mysql sql

我想用单个命令插入多个记录,我可以使用以下内容添加它们:

INSERT INTO MYTABLE (COL1,COL2,COL3) VALUES ("3","SHP","43-23"),("4", "KL", "54")

我可以添加多个记录,但现在我只想在该表中不存在该记录时插入。表是动态创建的,我不允许添加任何唯一列,所以我尝试插入如果不存在:

INSERT INTO b_branches (
     branch_name, branch_town, account_range_lower, account_range_upper
     ) SELECT
     'test BN'  branch_name,
     'test BT'    branch_town,
     'test ARL'    account_range_lower,
     'test ARU' account_range_upper
     FROM DUAL
     WHERE NOT EXISTS (
     SELECT 1
     FROM `b_branches`
     WHERE
     branch_name = 'test BN' AND branch_town = 'test BT' AND account_range_lower = 'test ARL'
     LIMIT 1 -- will stop mysql to stop searching after first match
     )

此代码有效,但通过此我只能一次添加一条记录,但我想在一个语句中添加所有记录。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以随时使用触发器。 但是我知道stop an Insert within a trigger is to cause a signal的唯一方法,它将回滚整个提交。