mysql 怎么修改某列为主键

mysql 怎么修改某列为主键,第1张

如果表之前有主键则先删除:

alter table 表名 drop constraint 主键名

修改主键:

alter table 表名 add constraint 主键名 primary key (column1,column2,....,column)

alter table t1 drop column c1

alter table t1 add column c1int identity

1.主键语法

①创建时:create table sc (

studentno int,

courseid int,

score int,

primary key (studentno) )

②修改时:ALTER TABLE table_name ADD CONSTRAINT pk_name PRIMARY KEY(列名)

前提是原先没有设置主键。

2.外键语法

①创建时:create table sc (

studentno int,

courseid int,

score int,

foreign key (courseid) )

②修改时:

ALTER TABLE news_info[子表名] ADD CONSTRAINT FK_news_info_news_type[约束名] FOREIGN KEY (info_id)[子表列] REFERENCES news_type[主表名] (id)[主表列]

3.使用组合主键

如果一列不能唯一区分一个表里的记录时,可以考虑多个列组合起来达到区分表记录的唯一性,形式

①创建时:create table sc (

studentno int,

courseid int,

score int,

primary key (studentno,courseid) )

②修改时:alter table tb_name add primary key (字段1,字段2,字段3)

前提是原来表中没有设置主键,若原先已有主键则会报错。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/8689638.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-19
下一篇 2023-04-19

发表评论

登录后才能评论

评论列表(0条)

保存