mysql優化學習on DUPLICATE key Update

場景:sql

有張表,裏面的記錄不能存在重複記錄,記錄存在就更新,若是不存在就插入併發

傳統作法:性能

先查詢select,若是存在就update,不存在就insert,這樣就存大兩條sql語句了。對於大併發來講,存在性能問題。spa

憂化方法:以下code

建立表,注意要有一個惟一索引 new_code_index, 插入或者更新時,以此爲標準blog

CREATE TABLE `news_test` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `new_title` varchar(255) DEFAULT NULL,
  `new_abstr` varchar(255) DEFAULT NULL,
  `new_code` varchar(255) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `new_code_index` (`new_code`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

sql語句索引

insert into news_test(new_title, new_abstr, new_code, update_time, create_time) values('馬刺','湖人',MD5(CONCAT('馬刺','湖人')), NOW(), NOW()) on DUPLICATE key Update update_time=now(), create_time=now();

第一次執行it

第二次執行class

相關文章
相關標籤/搜索