1. 创建表的同时添加外键

create table score(
score int(3),
st_id int(16),
cs_id int(16),
primary key(st_id,cs_id),
FOREIGN KEY (st_id) REFERENCES student(id),
FOREIGN KEY (cs_id) REFERENCES classes(id)
);

2. 已经创建表了怎么办:在表的定义外进行添加

alter table 表名 add constraint FK_ID foreign key(你的外键字段名) REFERENCES 外表表名(对应的表的主键字段名);

3.直接在属性值后面添加

create table score(
cscore int(11),
st_id int(50) references student(id),
cs_id int(30) references classes(id),
primary key(st_id,cs_id)
);

4.添加约束

create table score(
cscore int(11),
st_id int(50),
cs_id int(30),
primary key(st_id,cs_id),
CONSTRAINT `FK_ID_ST` FOREIGN KEY (st_id) REFERENCES student(id),
CONSTRAINT `FK_ID_CS` FOREIGN KEY (cs_id) REFERENCES classes(id)
);
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐