商品库存表
+------------+ +----------------+ +------------------+
| product | | product_store | | user_order |
+------------+ +----------------+ +------------------+
|id | <--+ |id | <---+ |id |
|price | +--1:1--o |product_id | | |user_id |
|quantity | |sn | +--1:n--o |product_store_id |
|... | |status | | |
|category_id | +----------------+ +------------------+
+------------+
product 是产品表总表,product_store每个产品一条记录,同时将sn编号对应到物理产品,这时记录库存需要 {http://netkiller.github.io/}
select count(id) from product_store where product_id='xxxxx' and status = 'sell'
商品销售
begin;
select id from product_store where status = 'sale' and product_id='xxxxx' for update;
insert into user_order(user_id,product_store_id) values('xxxxxx','xxxxx');
update product_store set status = 'sold' where status = 'sale' and product_id='xxxxx';
commit;
售出的商品与用户的订单项一一对应的。{http://netkiller.github.io/}
注意上面,这里使用了排它锁与事务处理,防止一个商品卖给两个人。
根据上面的思路我们可以将商品属性与product_store表进行一对一匹配,这样每个商品都有它自己的商品属性,甚至价格也可以移到product_store表中,例如不同颜色售价不同。