栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

我实际上并不建议您这样做,因为

UNIQUE
Piskvor和其他人建议的索引是一种更好的方法,但是您实际上可以做您想做的事情:

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  |+----+---------+-----------+------+


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369880.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号