希望此脚本有帮助...一切顺利:创建数据库并创建Catergory,Product_Has_Suppiers和Product表。当我尝试执行Suppliers'create table'语句时,它返回1215错误'无法添加外键约束'。
-- Create database
Create database if not exists FinalExam;
-- Use Database
Use FinalExamReview;
-- Create table
Create table if not exists Category(
Cat_id int primary key,
`name` varchar(50));
Create table if not exists Product_Has_Suppliers(
Product_Product_ID int,
Suppliers_Supplier_Code int,
Constraint PHS_Keys Primary key (Product_Product_ID,
Suppliers_Supplier_Code));
Create table if not exists Product(
Product_ID int auto_increment,
`Name` varchar(25) not null,
Price decimal(4,2) not null,
decription varchar(45),
last_update timestamp not null,
Category_Cat_ID int,
Foreign key (Category_Cat_ID) References Category(Cat_ID),
Foreign key (Product_ID) References
Product_Has_Suppliers(Product_Product_ID));
Create table if not exists Suppliers(
Supplier_Code int auto_increment,
`Name` varchar(45),
city varchar(25),
state char(2),
foreign key (Supplier_Code) References
product_has_suppliers(suppliers_supplier_code));
最佳答案
这可以修复您的错误:
Create table if not exists Categories (
category_id int primary key,
name varchar(50)
);
Create table if not exists Products (
Product_ID int auto_increment primary key,
Name varchar(25) not null,
Price decimal(4,2) not null,
decription varchar(45),
last_update timestamp not null,
category_id int,
Foreign key (category_id) References Categories(category_id)
);
Create table if not exists Suppliers (
Supplier_Id int auto_increment primary key,
Name varchar(45),
city varchar(25),
state char(2)
);
Create table if not exists Product_Has_Suppliers(
Product_ID int,
Supplier_Id int,
Constraint PHS_Keys Primary key (Product_ID,
Supplier_Code),
Foreign key (Product_ID) References
Products(Product_ID),
foreign key (Supplier_Id) References
Suppliers(Supplier_Id)
);
SQL Fiddle是here。
您似乎不明白什么?
首先,
Suppliers
和Products
是实体。实体具有主键,通常是自动递增的值。您将这些列定义为外键。但是主键是唯一标识每一行的键。其次,
Product_Has_Suppliers
是联结表(又名“关联”表)。它以多对多关系链接两个表(产品具有多个供应商,供应商提供多个产品。它应该与其他表具有外键关系。在此期间,我进行了一些其他更改,这些更改是我认为是最佳做法的:
表名都是复数的(它们是其中的实体的存储桶,应该有多个)。
主键是表名的单数,后跟
_id
。外键与主键具有相同的名称。这非常方便,因此您可以使用
using
子句-例如。如果遵循这些规则,则该代码是自记录的。您可以查看一个表,仅通过名称即可知道外键是指什么。
关于mysql - SQL在创建表错误中引用外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49391328/