您可以按照传统的方式进行操作...使用类似以下SQL语句的方式
ALTER TABLE table_1_name
ADD CONSTRAINT fk_foreign_key_name
FOREIGN KEY (table_1_column_name)
REFERENCES target_table(target_table_column_name);
books 的表,其中包含指向 users 表中 id 列的 created_by 列:
ALTER TABLE books
ADD CONSTRAINT books_FK_1
FOREIGN KEY (created_by)
REFERENCES users(id);
假设这些键已经存在于相关的表中
为应用外键约束,必须对关键字进行索引。按照以下步骤操作。
现在,您可以将DOCTOR_ID指定为外键。
ALTER TABLE Patient ADD CONSTRAINT fk_to_Doctorid FOREIGN KEY (Doctorid) REFERENCES Doctor(DoctorId);
在此之前,我是否需要为该列创建索引? - laurajscategories
表:CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;
products
表并引用 categories
表:CREATE TABLE products(
prd_id int not null auto_increment primary key,
prd_name varchar(355) not null,
prd_price decimal,
cat_id int not null,
FOREIGN KEY fk_cat(cat_id)
REFERENCES categories(cat_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
)ENGINE=InnoDB;
vendors
的表格,然后修改products
表格:CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
vendors
表)添加到products
表中,可以使用以下语句:ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;