mysql - 两列主键、自增、外键

标签 mysql auto-increment foreign-key-relationship composite-primary-key

以下查询成功,但是当我在订单 id 中输入空值并为项目 id 输入不同的值(列中不存在的值)时,订单 id 仍然会递增。如何保留相同的订单id?外键的表述方式有问题吗?

CREATE TABLE orders(
    orderid int not null auto_increment, 
    itemid int not null, 
    quantity int not null, 
    tot_price int not null, 
    cid int not null, 
    code varchar(10), 
    order_time time, 
    order_date date ,
    constraint order_pk primary key (orderid, itemid), 
    foreign key (itemid) references items(itemid), 
    foreign key (cid) references customer(cid), 
    foreign key (code) references coupon(code)
);

最佳答案

问题源于尝试在单个表中执行一对多(订单到项目)关系。这会很糟糕地结束。你需要两个。一份用于订单,一份用于订单中的项目。无论好坏,这就是关系数据库做列表的方式。

CREATE TABLE orders (
    orderid int not null primary key auto_increment, 
    cid int not null references customer(cid),
    code varchar(10) references coupon(code),

    when_ordered datetime,
    INDEX(when_ordered)
);

CREATE TABLE items_in_an_order (
    orderid int not null references orders(id),
    itemid int not null references items(id),

    quantity int not null,
    price_paid int not null
);

quantity 移动到 items_in_an_order。我将 total_price 更改为更具描述性的 price_paid,这可能更能描述您想要存储的内容。这将让您生成收据。

order_dateorder_time 不必要地分成两列。这使得比较和排序变得很尴尬。将它们放在一个 DATETIME 列中并对其建立索引将允许您按日期/时间排序并检查订单是否在日期/时间范围内。

要获取订单中的所有商品,do a join .

SELECT items.itemid
FROM   items
JOIN   items_in_an_order io ON io.itemid = items.id
WHERE  io.orderid = ?

要查找某个商品所在的所有订单,还需要执行联接。

SELECT orders.id
FROM   orders
JOIN   items_in_an_order io ON io.orderid = orders.id
WHERE  io.itemid = ?

关于mysql - 两列主键、自增、外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802726/

相关文章:

php - Laravel 5.0 : Querying and displaying child objects in view from nested relationship

mysql - 无法删除外键

php - 排行榜 - MySQL 按个人总和排序

mysql - 获取与至少一名其他员工同时进入项目的所有员工的名字和姓氏

mysql - 在非主键列上为 Autoiuncrement 列指定默认起始值​​?

mysql - 如何阻止 auto_increment 将下一个数字始终设置为 maxnumber + 1

mysql - 如果自增值达到极限怎么办?

php - 如何通过表单输入添加新表和列

c# - 已经有一个打开的 DataReader 与此连接关联,必须先将其关闭。 C# 与 mysql 数据库

mysql - 如何更改外键引用 Action ? (行为)