mysql - alter语发

本文详细介绍了如何在MySQL中使用ALTER TABLE进行字段的添加、删除、位置调整和类型变更,包括示例操作与注意事项。从创建表开始,逐步演示了如何维护数据库结构的灵活性。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

select version();

-- 5.7.31-log

-- mysql - alter的运用

use mysql_study;

drop table if exists `test_alter`;

create table if not exists `test_alter`

(

    `id` int unsigned auto_increment,

    `name` varchar(50),

    `pwd` char(48),

    `add_time` date,

    primary key(`id`)

)engine = innodb default charset=utf8;

show columns from `test_alter`;

-- 添加字段

alter table `test_alter` add `test` tinyint;

show columns from `test_alter`;

-- 删除字段

alter table `test_alter` drop `test`;

show columns from `test_alter`;

-- 添加字段并位于第一列或者某一列之后

alter table `test_alter` add `field_one` int first;

show columns from `test_alter`;

alter table `test_alter` add `after_pwd` tinyint after `pwd`;

show columns from `test_alter`;

-- 调整字段的顺序

alter table `test_alter` modify `name` varchar(50) first;

show columns from `test_alter`;

alter table `test_alter` modify `name` varchar(50) after `id`;

show columns from `test_alter`;

-- 修改存储引擎

alter table `test_alter` engine = innodb;

show table status like 'test%';

-- 删除外键关系

#alter table `test_alter` drop foreign key keyName;

-- 修改字段类型 modify

alter table `test_alter` modify `pwd` varchar(50);

show columns from `test_alter`;

-- 修改字段类型 change

alter table `test_alter` change `pwd` `pwd` varchar(48);

show columns from `test_alter`;

alter table `test_alter` change `pwd` `old_pwd` char(48);

show columns from `test_alter`;

insert into `test_alter`(`name`) values('张三');

delete from `test_alter`;

update `test_alter` set add_time = now();

select from `test_alter`;

-- alter 对null值和默认值的影响

alter table `test_alter` modify `add_time` date not null; #在有数据的情况下不能修改为非空,可以将null的数据默认指定值

-- 所以在MYSQL中,如果想要插入时自动获取当前时间,则需要使用timestamp类型,然后赋默认值就可以了。

alter table `test_alter` alter column `old_pwd` set default '123456';

show columns from `test_alter`;

select from `test_alter`;

-- 删除默认值

alter table `test_alter` alter `old_pwd` drop default;

show columns from `test_alter`;

-- 修改表名

alter table `test_alter` rename to `test_alter1`;

alter table `test_alter1` rename to `test_alter`;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值