想象一个数据库设置,其中 x 个客户可以下 y 个订单。 通常所有客户都会共享一组自动递增的订单 ID。
- 客户 A 的第一个订单的订单 ID 为 #1
- 客户 B 的第一个订单的订单 ID 为 #2。
我希望为每个客户提供单独的订单 ID 集。重要的是,客户无法根据 id 查看有多少其他客户下过订单。
- 客户 A 的第一个订单的订单 ID 为 #1
- 客户 A 的第二个订单的订单 ID 为 #2
- 客户 B 的第一个订单的订单 ID 为 #1
目前,我能看到的唯一方法是手动选择客户订单号的最大值,添加+1,然后手动插入。
select max(customer_order_id) from orders where customer_id = X
如何从数据完整性和规范化的角度创建这种方法?比如为客户的各个订单 ID 提供某种自动增量?
create table customers
(
id int auto_increment primary key,
name varchar(255)
);
create table orders
(
id int auto_increment primary key,
customer_id int
customer_order_id int
foo varchar
bar varchar
);
最佳答案
只需将订单号设为客户编号,后跟序列号即可。因此,如果我是客户 103985,我的第一个订单是 103985-0001,我的第二个订单是 103985-0002。标准化数据——在订单中,分别存储客户编号和序列号。将它们组合起来进行显示。
关于mysql - 如何为每个客户 ID 提供单独的订单 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9221354/