寫(xiě)在前面
使用MySQL的刪、改、查功能時(shí),我們都可以根據(jù)where條件來(lái)對(duì)指定數(shù)據(jù)進(jìn)行操作。
插入語(yǔ)句如何通過(guò)where條件,來(lái)判斷是否允許插入呢?
根據(jù)條件插入數(shù)據(jù)
1、先準(zhǔn)備測(cè)試數(shù)據(jù)
2、正常的插入語(yǔ)句
insert into `test_table` (id, content) values('3', '內(nèi)容3');
此時(shí)表里有三條數(shù)據(jù)了:
3、有條件的插入語(yǔ)句(重點(diǎn))
insert into `test_table` (id, content)
select * from (select '4' AS id, '內(nèi)容4' AS content) as tmp
where not exists ( select 1 from `test_table` where id = 1 ) limit 1;
上面sql執(zhí)行結(jié)果:
insert into
test_table
(id, content)
select * from (select ‘4’, ‘內(nèi)容4’) as tmp
where not exists ( select 1 fromtest_table
where id = 1 ) limit 1
Affected rows: 0
時(shí)間: 0.018s
insert into `test_table` (id, content)
select * from (select '4' AS id, '內(nèi)容4' AS content) as tmp
where not exists ( select 1 from `test_table` where id = 4 ) limit 1;
上面sql執(zhí)行結(jié)果:
insert into
test_table
(id, content)
select * from (select ‘4’, ‘內(nèi)容4’) as tmp
where not exists ( select 1 fromtest_table
where id = 4 ) limit 1
Affected rows: 1
時(shí)間: 0.018s
4、查看最終結(jié)果
5、使用INSERT IGNORE INTO(重點(diǎn))
insert ignore into `test_table` (id, content) values('3', '內(nèi)容3');
insert ignore into
test_table
(id, content) values(‘3’, ‘內(nèi)容3’)
Affected rows: 1
時(shí)間: 0.024s
insert ignore into
test_table
(id, content) values(‘3’, ‘內(nèi)容3’)
Affected rows: 0
時(shí)間: 0.023s
如果有唯一性約束,可以使用INSERT IGNORE INTO,判斷插入的行數(shù)。
總結(jié)分析
我們使用insert into語(yǔ)句做了個(gè)取巧,我們都知道insert into語(yǔ)句有以下用法:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-408006.html
-- 插入一條
INSERT INTO t1(field1,field2) VALUE(v001,v002);
-- 批量插入
INSERT INTO t1(field1,field2) VALUES(v101,v102),(v201,v202),(v301,v302),(v401,v402);
-- 指定字段
INSERT INTO t2(field1,field2) SELECT col1,col2 FROM t1 WHERE ……
-- 當(dāng)t2、t1表結(jié)構(gòu)相同時(shí)
INSERT INTO t2 SELECT id, name, address FROM t1
我們這里使用第三種方式,自定義了一個(gè)臨時(shí)表,臨時(shí)表的數(shù)據(jù)就是我們要insert的數(shù)據(jù),此時(shí)的臨時(shí)表就可以寫(xiě)where條件了!文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-408006.html
到了這里,關(guān)于MySql按條件插入數(shù)據(jù),MySQL插入語(yǔ)句寫(xiě)where條件,MySQL在插入時(shí)做冪等的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!