沒有驚喜,這個已經到來之前prevent autoincrement on MYSQL duplicate insert
我喜歡這個解決方案
INSERT INTO COMPANY (NAME) SELECT 'TEST' AS INNAME FROM DUAL
WHERE NOT EXISTS(
SELECT NAME FROM COMPANY
WHERE NAME = 'TEST'
LIMIT 1
);
MariaDB [sandbox]> DROP TABLE IF EXISTS COMPANY;
Query OK, 0 rows affected (0.12 sec)
MariaDB [sandbox]> CREATE TABLE COMPANY (ID INT AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(10), UNIQUE (NAME));
Query OK, 0 rows affected (0.24 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO COMPANY (NAME) VALUES ('TEST');
Query OK, 1 row affected (0.08 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO COMPANY (NAME) SELECT 'TEST' AS INNAME FROM DUAL
-> WHERE NOT EXISTS(
-> SELECT NAME FROM COMPANY
-> WHERE NAME = 'TEST'
-> LIMIT 1
->);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO COMPANY (NAME) SELECT 'ABC' AS INNAME FROM DUAL
-> WHERE NOT EXISTS(
-> SELECT NAME FROM COMPANY
-> WHERE NAME = 'ABC'
-> LIMIT 1
->);
Query OK, 1 row affected (0.10 sec)
Records: 1 Duplicates: 0 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]> SELECT * FROM COMPANY;
+----+------+
| ID | NAME |
+----+------+
| 2 | ABC |
| 1 | TEST |
+----+------+
2 rows in set (0.00 sec)
請更新您的問題,並說明你究竟想在這裏發生什麼。 –
@TimBiegeleisen我不知道如何更清楚地描述它。如果名稱不存在(應該在表被填充時已經有效)或者表爲空(當表爲空時,當前查詢不起作用),它應該插入。所以唯一的錯誤是在表空時修復它。 –
我似乎無法重現你的例子([見這裏](http://rextester.com/SJN88611))。也許你應該給一個可重複的例子。 –