消费事务会产生 SQL 数据: SELECT * FROM `api_credits` WHERE `uid`='22' LIMIT 1 UPDATE `api_credits` SET `credits1`=`credits1`-'100' WHERE `uid`='22' AND `credits1`>='100' INSERT INTO `api_credits_log` SET `uid`='22', `cid`='3', `credits`='100', `balance`='79900', `time`='1701001020'
-- 步骤一:先变更,这样会锁住 `uid`='22' 这条记录,别的会话只能查询,不能变更 UPDATE `api_credits` SET `credits1`=`credits1`-'100' WHERE `uid`='22' AND `credits1`>='100' -- 步骤二:拿到变更后的最新的积分余额 SELECT * FROM `api_credits` WHERE `uid`='22' LIMIT 1 -- 将步骤二中获取到的积分余额插入到积分记录表中 INSERT INTO `api_credits_log` SET `uid`='22', `cid`='3', `credits`='100', `balance`='79900', `time`='1701001020'
你需要的是更新并查询, 在 MySQL 中可以使用变量来记录更新后的值, 然后在更新语句后查询该变量值, UPDATE `api_credits` SET `credits1`= @xxx := `credits1`-'100' WHERE `uid`='22' AND `credits1`>='100' INSERT INTO `api_credits_log` SET `uid`='22', `cid`='3', `credits`='100', `balance`='79900', `time`='1701001020'; select @xxx;