針對不明確insert還是update的操作,mysql數據庫表設計

replace into

注意,如果有多個唯一鍵,那麼執行結果可能合併減少記錄數。

  • sqlserver
   if not exists (select 1 from t where id = 1)
      insert into t(id, update_time) values(1, getdate())
   else
      update t set update_time = getdate() where id = 1
  • mysql
1. replace into tbl_name(col_name, ...) values(...)
2. replace into tbl_name(col_name, ...) select ...
3. replace into tbl_name set col_name=value, ...

ON DUPLICATE KEY UPDATE

CREATE TABLE `willow_player` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `player_id` bigint(16) NOT NULL DEFAULT '0',
  `num` int(11) NOT NULL DEFAULT '0',
  `award_type` tinyint(4) NOT NULL DEFAULT '0' COMMENT '類型',
  `repeat_num` smallint(11) NOT NULL DEFAULT '0' COMMENT '重複輪數',
  PRIMARY KEY (`id`),
  UNIQUE KEY `num` (`player_id`,`award_type`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=utf8mb4;

#以前寫法:
select  num  from 表名 where  uid=20001 and  award_type=0 limit 1;
 update 表名 set  num=num+1 where  uid=20001 and  award_type=0

#現在
insert into table (player_id,award_type,num)  values(20001,0,1) on  DUPLICATE key update num=num+values(num)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章