1. 程式人生 > >mysql_表_操作

mysql_表_操作

rst chang 數據類型 null ima blog 外鍵 清空表 des

1、創建表

# 基本語法:
create table 表名(
    列名  類型  是否可以為空  默認值  自增  主鍵,
    列名  類型  是否可以為空
)ENGINE=InnoDB DEFAULT CHARSET=utf8

not null         # 不可以為空
default 1        # 默認值為1
auto_increment   # 自增
primary key      # 主鍵
constraint 外鍵名 foreign key (從表字段’自己‘) references 主表(主鍵字段)    # 外鍵

技術分享圖片

2、查看表結構

desc 表名

技術分享圖片

3、刪除表

drop table 表名

技術分享圖片

4、清空表

# 表還存在,表內容清空

delete from 表名
truncate table 表名

技術分享圖片

5、修改表

# 添加列:
        alter table 表名 add 列名 類型

技術分享圖片

# 刪除列:
        alter table 表名 drop column 列名

技術分享圖片

# 修改列數據類型:
        alter table 表名 modify column 列名 類型; 

技術分享圖片

# 修改列數據類型和列名:
    alter table 表名 change 原列名 新列名 類型; 

技術分享圖片

# 添加主鍵:
        alter table 表名 add primary key(列名);
# 刪除主鍵:
        alter table 表名 drop primary key;
# 添加外鍵:
        alter table 從表 add constraint 外鍵名稱(形如:FK_從表_主表) foreign key 從表(外鍵字段) references 主表(主鍵字段);
# 刪除外鍵:
        alter table 表名 drop foreign key 外鍵名稱
# 修改默認值:
        ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
# 刪除默認值:
        ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
# 更改表名
         rename table 原表名 to 新表名;

技術分享圖片

#增加表字段,altertable法。
1>    語法: altertable 表名 add 字段 類型 其他;
2>    插入列,名為sex。
mysql> alter table student add sex char(4);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from student;
+----+----------+-----+------+------+
| id | name     | age | dept | sex  |
+----+----------+-----+------+------+
|  2 | oldsuo   |   0 | NULL | NULL |
|  3 | kangknag |   0 | NULL | NULL |
|  4 | kangkang |   0 | NULL | NULL |
+----+----------+-----+------+------+
3 rows in set (0.00 sec)
3>    插入名為suo列在name後面。
mysql> alter table student add suo int(4) after name;
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0
4>    插入名為qq列在第一。
mysql> alter table student add qq varchar(15) first;
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

參考:https://www.cnblogs.com/suoning/articles/5769141.html

mysql_表_操作