怎样用SQL语句在MYSQL中创建外键约束关系

我的表都是用MYSQL建的,不是用代码写的
2025-01-25 03:56:35
推荐回答(4个)
回答1:

应该是这样子的,
Alter table 表名
add foreign key (外键属性) references 表名(表属性)

回答2:

alter table table_name add constraint fk_column_id foreign key(column) references 

主键表 (column_id);

回答3:

alter table table_name add constraint fk_column_id foreign key(column) references 主键表 (column_id);

回答4:

给你个创建了外间约束的例子
看下,这个是我写的,字段多了些,不影响
create table if not exists entity(id int auto_increment primary key, hostname char(255), hostip char(32), type int, caption char(255), INDEX (id)) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci
create table if not exists hvhost(en_id int, username char(255), password char(255), memory_size bigint, cpu_count int, cpu_frequency bigint, power_state char(16), time char(64), FOREIGN KEY(en_id) REFERENCES entity(id) on delete cascade on update cascade) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci