MySQL:如果表中不存在插入记录

我正在尝试执行以下查询:

INSERT INTO table_listnames (name, address, tele)
VALUES ('Rupert', 'Somewhere', '022')
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name='value'
);

但是这会返回一个错误。 基本上我不想插入一条记录,如果记录的“名称”字段已经存在于另一条记录中 - 如何检查新名称是否是唯一的?


我并不是在暗示你这样做,因为Piskvor和其他人建议的UNIQUE索引是一种更好的方法,但实际上你可以做你想做的事情:

CREATE TABLE `table_listnames` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `tele` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

插入一条记录:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
+----+--------+-----------+------+

尝试再次插入相同的记录:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
+----+--------+-----------+------+

插入不同的记录:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'John', 'Doe', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'John'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
|  2 | John   | Doe       | 022  |
+----+--------+-----------+------+

等等...


INSERT在语法中不允许WHERE

你可以做什么:在应该是唯一的( name )字段上创建一个UNIQUE INDEX ,然后使用:

  • 正常INSERT (如果名称已经存在,则处理错误)
  • INSERT IGNORE (如果名称已经存在,它会静默失败导致警告(而不是错误)
  • INSERT ... ON DUPLICATE KEY UPDATE (如果名称已存在,将在最后执行UPDATE ,请参阅文档)

  • 工作:

    INSERT INTO users (full_name, login, password) 
      SELECT 'Mahbub Tito','tito',SHA1('12345') FROM DUAL
    WHERE NOT EXISTS 
      (SELECT login FROM users WHERE login='tito');
    
    链接地址: http://www.djcxy.com/p/58671.html

    上一篇: MySQL: Insert record if not exists in table

    下一篇: MySQL atomic insert