mysql 查詢不存在則插入
阿新 • • 發佈:2018-12-03
- 摘要:CREATETABLE`test1`(`id`int(10)unsignedNOTNULLAUTO_INCREMENT,`item_no`varchar(10)NOTNULLDEFAULT'',`delete_flag`tinyint(3)unsignedNOTNULLDEFAULT'0',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=5DEFAULTCHARSET=latin1insertintotest1(item_no,del
-
建立表:CREATE TABLE `test1` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `item_no` varchar(10) NOT NULL DEFAULT '', `delete_flag` tinyint(3) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
不存在則新增,新增則忽略 -
insert into test1 (item_no,delete_flag) select 'aaaaa',0 from dual where not exists ( select `item_no`,`delete_flag` from test1 where item_no='aaaaa' and delete_flag=0 );
例:
INSERT INTO `weixin_article_test`(artID, gzh_en, title, cover, summary, oriDate, content, ori_url, read_url) SELECT '203924112_1', 'ynluxiren', '”瀘西人“公眾微訊號正式開通啦', 'http://mmbiz.qpic.cn/mmbiz/JTA2OOtPMnjd2URJqg9niariaMHGzibZgruXqiaGYv7d8y95D15wwMlYOd41bcBqeRtb4N1uv2rKqKkSBGaGkcTqog/0', '力致於為全瀘西人服務的微信公眾號“瀘西人”開通啦', '2015-03-02 21:27:53', '', 'http://mp.weixin.qq.com/s?__biz=MzA3ODQwODM2NQ==&mid=203924112&idx=1&sn=13eb74e51bdd0669a2e06f93e8b768e8#rd', '' FROM dual WHERE NOT EXISTS ( Select * from `weixin_article_test` where `gzh_en`='ynluxiren' AND `artID` = '203924112_1' )
//使用 dual 做表名可以讓 select 語句後面直接跟上要insert欄位的值,即使這些值還不存在當前表中.