普通的 INSERT INTO 插入:sql
INSERT INTO card(cardno, cardnum) VALUES('1111', '100'); INSERT INTO card(cardno, cardnum) VALUES('2222', '200'); ...
對於普通的 INSERT 插入,若是想要保證不插入重複記錄,咱們只有對某個字段建立惟一約束實現(好比:cardno卡號不能重複);code
那有沒有不建立惟一約束,僅經過 INSERT INTO 一條語句實現的方案呢?get
答案:有的, INSERT INTO IF EXISTS 具體語法以下:io
INSERT INTO table(field1, field2, fieldn) SELECT 'field1', 'field2', 'fieldn' FROM DUAL WHERE NOT EXISTS(SELECT field FROM table WHERE field = ?)
其中的 DUAL 是一個臨時表,不須要物理建立,這麼用便可。針對上面的card示例的改造以下:table
INSERT INTO card(cardno, cardnum) SELECT '111' as cardno, '100' as cardnum FROM DUAL WHERE NOT EXISTS(SELECT cardno FROM card WHERE cardno = '111'); INSERT INTO card(cardno, cardnum) SELECT '222' as cardno, '200' as cardnum FROM DUAL WHERE NOT EXISTS(SELECT cardno FROM card WHERE cardno = '222');
搞定!語法
關於duplicate column問題,解決方案:https://stackoverflow.com/questions/3346351/insert-record-if-not-exists-in-sql-duplicate-column-namestackoverflow