看板 Database 關於我們 聯絡資訊
資料庫名稱: Aurora mySQL 資料庫版本: 內容/問題描述: 我有一個表格 Schema CREATE TABLE `credit` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `company_id` int(10) unsigned NOT NULL, `agent_id` int(10) unsigned NOT NULL, `balance_before` decimal(15,5) NOT NULL, `amount` decimal(15,5) NOT NULL, `balance_after` decimal(15,5) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `agent_amount` (`agent_id`,`amount`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 我在做交易的時候下了 SELECT * FROM credit Where agent_id = "{agent_id}" FOR UPDATE UPDATE credit set amount = "amount" WHERE agent_id = "{agent_id}" 在高併發的情境下,很容易發生 DeadLock 請問如果我的索引是用複合索引,是否不會是行鎖而是表鎖 謝謝回覆 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.180.80.96 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Database/M.1650964479.A.BF0.html
parkerchung: 可以試試看把agent_id 加上index 04/28 16:14
arcade0425: 比較粗略的解釋(概念上不完全正確), 05/01 14:10
arcade0425: for update 鎖的不是行,是 index,你在第一個 trx 05/01 14:10
arcade0425: 改變了原本的 index,原本被卡住的第二個 trx 等到鎖 05/01 14:10
arcade0425: 終於釋放時找不到自己要鎖的 index 在哪,mysql 就幫 05/01 14:10
arcade0425: 你 rollback 第二個 trx 了 05/01 14:10
arcade0425: 解法上建議是直接把原本建的 index 刪除,再把 agent 05/01 14:13
arcade0425: _id 單獨加 index,只多加一個 index 但沒有把原本的 05/01 14:13
arcade0425: index 刪除, query 可能還是會使用原本兩個一起的 05/01 14:13
arcade0425: index 造成 Deadlock 05/01 14:13