SQL实现限购?

发布于 2015-09-26 / MySQL / 0条评论 / 1,970浏览

多用户同时买限购一件的商品

数据库简略模型
table name : product

+--------------------------
|  id  |  stock  |  version
+--------------------------
|  123 |  3      |  2
+--------------------------

example 0:

update product set stock = stock - 1 where id = 123;

example 1:

update product set stock = stock - 1 where id = 123 and version = 2;

example 2:

update product set stock = stock - 1 where id = 123 and stock >= stock - 1;

example 3:

update product set stock = stock - 1 where id = 123 and stock > 0;

这个有4个解答,请问哪个能实现需求?或许有更完美的答案…

欢迎评论 (看不懂的就点赞吧)

不要纠结为什么是从0开始…

评论
站长统计