我实际上并不建议您这样做,因为
UNIQUEPiskvor和其他人建议的索引是一种更好的方法,但是您实际上可以做您想做的事情:
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 tmpWHERe 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: 0SELECt * 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 tmpWHERe 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 tmpWHERe 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: 0SELECt * FROM `table_listnames`;+----+--------+-----------+------+| id | name | address | tele |+----+--------+-----------+------+| 1 | Rupert | Somewhere | 022 || 2 | John | Doe | 022 |+----+--------+-----------+------+
等等…
更新:
为了防止
#1060 - Duplicate column name在两个值相等的情况下出错,您必须命名内部SELECt的列:
INSERT INTO table_listnames (name, address, tele)SELECT * FROM (SELECt 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmpWHERe 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: 0SELECt * FROM `table_listnames`;+----+---------+-----------+------+| id | name | address | tele |+----+---------+-----------+------+| 1 | Rupert | Somewhere | 022 || 2 | John | Doe | 022 || 3 | Unknown | Unknown | 022 |+----+---------+-----------+------+



