SQL alter 改变表结构,join表连接

join 连接,作用是:多表查询

利用两个表中共同含有的列的相同值来连接

select 列名 from 第一个表,第二个表

where 第一个表.列名 = 第二个表.列名

inner join内连接:

select 表1.*,表2.* from 表1 inner join 表2 on 表1.列名 = 表2.列名

left join 左连接:

select 表1.*,表2.* from 表1 left join 表2 on 表1.列名 = 表2.列名

right join 右连接:

select 表1.*,表2.* from 表1 right join 表2 on 表1.列名 = 表2.列名

union:综合多个select语句,且返回不重复的行

select 列名1,列名2,列名n from 表名

where 条件

union

select 列名1,列名2,列名n from 表名

where 条件;

【注意】

1.每个select语句中必须选中数目相同的列

2.列的数据类型要一致

3.列的顺序要一致

alter 改变表的结构

添加列

alter table 表名 add 列名 数据类型【default 默认值】;

【】中括号在python注释中表示选填,括号类表示为新加的列设定默认值

删除列

alter table 表名 drop column 列名;

修改表中某列数据类型

alter table 表名 modify column 列名 数据类型

修改表名

alter table 表名 rename 新的名字;

修改列名

alter table 表名 change 旧名字 新名字 数据类型;

对表添加唯一限制:

alter table 表名 add constraint MyUniqueConstraint unique(列名1,列名2,列名n)

对表取消唯一限制

alter table 表名 drop index MyUniqueConstraint;

对标添加主键限制:

alter table 表名 add primary key(列名1, 列名2,列名n)

对表取消主键限制:

alter table 表名 drop primary key;

对表添加外键限制:

alter table 表名 add foreign key(列名1,列名2,列名n) reference 另一个表名

对表取消外键限制:

alter table 表名 drop foreign key 自动生成的外键限制名;

【注意】

1.show create table 查看系统自动生成的限制名

2.限制名不是外键名

对表添加非空限制:

alter table 表名 modify 列名 数据类型 not null;

truncate table 表名;

保留表头,保留表的格式,只删除表中存放数据

【说明】

1.truncate table 与 delete table 效果一样

2.drop table 不仅删除表中数据,连表的骨架一起删除,不是对这个表有深仇大恨就慎用


猜你喜欢

转载自blog.csdn.net/qq_41802773/article/details/80373970