简体   繁体   English

当我在mysql中有外键时如何插入列

[英]How can I do an insert into to a column when I have a foreign key in mysql

Hello guys I have some problems I have been trying to inser data to a column which have a foreign key in MSQL But I can't make it work. 大家好,我一直在尝试将数据插入到在MSQL中具有外键的列中遇到一些问题,但我无法使其正常工作。 I would appreciate if somebody help me with this. 如果有人帮助我,我将不胜感激。

 Category
(
 idCategory int(20) auto_increment not null,
 NameCategory varchar(40) not null,
 PRIMARY KEY (idCategory)
);

SubCategory
( 
 idSubCategory int(10)not null primary key auto_increment ,
 NameSub varchar(40) not null,
 FK_Category int not null 
);

ALTER TABLE SubCategory auto_increment=1;

ALTER TABLE SubCategory
ADD FOREIGN KEY (PK_Category)
REFERENCES Category (idCategory);

I have tried this 3 ways but nothing works 我已经尝试了这3种方式,但没有任何效果

INSERT INTO Subcategory (NameSub)
VALUES ( 'Nisan');

INSERT INTO Subcategory (idSubCategory, NameSub,PK_Category)
VALUES (01, 'Nisan', 01);

INSERT INTO subcategory (NameSub, PK_Category) VALUES
    ( 'Nisan' SELECT idCategory from Category WHERE idCategory = 1 );

For some reason your Foreign key constrains script didn't work for me so I did it another an alternate way. 由于某种原因,您的外键约束脚本对我不起作用,因此我以另一种方式进行了操作。
I worked out why afterwards, you reference you have ADD FOREIGN KEY (PK_Category) rather than (FK_Category) 我弄清楚了为什么之后,您引用您具有ADD FOREIGN KEY (PK_Category)而不是(FK_Category)

CREATE TABLE Category
(
 idCategory int(20) auto_increment not null,
 NameCategory varchar(40) not null,
 PRIMARY KEY (idCategory)
);

CREATE TABLE SubCategory
( 
 idSubCategory int(10)not null primary key auto_increment ,
 NameSub varchar(40) not null,
 FK_Category int not null,
 INDEX IDX_Category(FK_Category),
 FOREIGN KEY (FK_Category) 
        REFERENCES Category(idCategory)
        ON DELETE CASCADE  
);


ALTER TABLE SubCategory auto_increment=1;

And here are the inserts 这是插入

INSERT INTO Category (NameCategory)
VALUES ('Car');

INSERT INTO Subcategory (NameSub,FK_Category)
VALUES ('Nisan', 01);

As you didn't specify the contents of the table of Category I've created one. 由于您未指定Category表的内容,因此我创建了一个。

Note: The issue you may be having is that your parent table is empty, and then it would error. 注意:您可能遇到的问题是您的父表为空,然后会出错。

SQL Fiddle SQL小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM