Home > Database > Mysql Tutorial > MySQL INSERT插入条件判断_MySQL

MySQL INSERT插入条件判断_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 13:11:29
Original
1201 people have browsed it

普通的 INSERT INTO 插入:

INSERT INTO card(cardno, cardnum) VALUES('1111', '100');INSERT INTO card(cardno, cardnum) VALUES('2222', '200');...
Copy after login

对于普通的 INSERT 插入,如果想要保证不插入重复记录,我们只有对某个字段创建唯一约束实现(比如:cardno卡号不能重复);

那有没有不创建唯一约束,仅通过 INSERT INTO 一条语句实现的方案呢?

答案:有的, INSERT INTO IF EXISTS 具体语法如下:

INSERT INTO table(field1, field2, fieldn) SELECT 'field1', 'field2', 'fieldn' FROM DUAL WHERE NOT EXISTS(SELECT field FROM table WHERE field = ?)
Copy after login

其中的 DUAL 是一个临时表,不需要物理创建,这么用即可。

针对上面的card示例的改造如下:

INSERT INTO card(cardno, cardnum) SELECT '111', '100' FROM DUAL WHERE NOT EXISTS(SELECT cardno FROM card WHERE cardno = '111');INSERT INTO card(cardno, cardnum) SELECT '222', '200' FROM DUAL WHERE NOT EXISTS(SELECT cardno FROM card WHERE cardno = '222');
Copy after login

搞定!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template