外键不会自动增加

时间:2016-02-05 08:22:21

标签: php mysql

我的代码:

enter image description here

    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 
    )

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

1 个答案:

答案 0 :(得分:0)

进行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?