【问题标题】:Foreign key doesn't get auto_incremented外键没有自动递增
【发布时间】:2016-02-05 08:22:21
【问题描述】:

我的代码:

    create table Products
(
    ProductID int not null auto_increment primary key,
    ProductName varchar(20),
    Recommendedprice decimal(10,2),
    Category varchar(10)

)



create table customers
(
    CustomerID int not null auto_increment primary key,
    FirstName varchar(50),
    LastName varchar(50),
    city varchar(50),
    State char(2),
    zip varchar(10)

)


    create table sales
    (
        SalesID int not null auto_increment primary key,
        ProductID int, 
        CustomerID int,
        CONSTRAINT fk_PerProducts FOREIGN KEY (ProductId)
        REFERENCES Products(ProductId),  
        CONSTRAINT fk_PerCustomers FOREIGN KEY (CustomerId)
        REFERENCES customers(customerId),  
        SalesPrice decimal(10,2),
        SalesDate date 
    )

我在表格列表中得到空值。

【问题讨论】:

  • 创建数据库实践 创建表 Products ( ProductID int not null auto_increment 主键, ProductName varchar(20), Recommendedprice decimal(10,2), Category varchar(10) ) 创建表 customers ( CustomerID int not null auto_increment 主键,FirstName varchar(50),LastName varchar(50),city varchar(50),State char(2),zip varchar(10))
  • 你能再具体一点吗?
  • 查询的是什么?你有left join 桌子吗?
  • 有没有人可以帮助摆脱这种情况? :D
  • no....我只在创建表语句中使用了两个外键....应该有整数值,但我得到的是 Null 值....不知道为什么?需要一些修改吗?我是初学者!

标签: php mysql


【解决方案1】:

在进行 INSERT 时需要发送外键的 id。

像这样(paper_Author 像你的 sales 表一样工作):

CREATE TABLE Paper (`paperId` int, `title` varchar(7));
INSERT INTO Paper (`paperId`, `title`)
VALUES (1, 'hello'),(2, 'hola'),(3, 'bonjour');

CREATE TABLE Author (`authorId` int, `authorName` varchar(3));
INSERT INTO Author (`authorId`, `authorName`)
VALUES (1, 'me'),(2, 'moi');

CREATE TABLE Paper_Author (`paperId` int, `authorId` int);
INSERT INTO Paper_Author (`paperId`, `authorId`)
VALUES (1, 1),(1, 2),(2, 2);

然后你像这样使用它: http://sqlfiddle.com/#!2/eb61f/2


其他人认为你应该阅读:

Basics of Foreign Keys in MySQL?

Why use Foreign Key constraints in MySQL?

【讨论】:

  • 所以结论是:我必须自己插入外键的值。它不会来自主表?
  • 是的,如果我手动插入它可以工作。谢谢。我以为它会来自小学,但那不是真的。我猜!
  • 您的代码无法猜测您要链接的内容。 id 主键在这里是一个唯一标识符,您可以在其他表中使用以引用整行(如产品上的闪存代码)。如果在innoDB mySql DB 上使用该约束,如果您仍有一个属于该行的子行,该约束将锁定该行。这使您可以保持数据完整性(没有孤立)。
  • 我理解我的错误。我没有清楚地看到销售表。所以我被困在了错误的方式中。最后我摆脱了它。感谢堆栈溢出!以及你们所有人的回应!
猜你喜欢
  • 2016-09-06
  • 2016-04-22
  • 1970-01-01
  • 2015-11-13
  • 2012-02-15
  • 1970-01-01
  • 2023-03-26
  • 2013-09-28
  • 2019-09-26
相关资源
最近更新 更多