MySQL表更改ALTER,CHANGE,MODIFY的区别
Posted 白-胖-子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL表更改ALTER,CHANGE,MODIFY的区别相关的知识,希望对你有一定的参考价值。
太长不看,这三个命令主要是对表的属性进行修改,就像对excel中一个Sheet进行标签重命名,首行列名更改,列内单元格格式修改,列位置调换等这些非数据的表格属性新修改
- ALTER 修改命令总入口,不光可以修改表,还可以修改数据库、用户、环境变量等等
- CHANGE 主要用来给COLUMN也就是列名来重命名用的
- MODIFY 改变数据类型,移动位置之类修改列属性,除了重命名
mysql表增删改查
- 表是关系型数据库的最大特征
- 数据都以关系的方式存放在表中
创建表
CREATE TABLE [IF NOT EXISTS] 'tbl_name' (col1 type1 修饰符, col2 type2 修饰符, ...)
查看表
- 查看表
SHOW TABLES [FROM db_name]
- 查看表结构
DESC [db_name.]tb_name
- 查看表状态
SHOW TABLE STATUS LIKE 'tbl_name'
- 查看表中数据
SELECT * FROM students WHERE id < 3;
SELECT * FROM students WHERE gender='m';
SELECT * FROM students WHERE gender IS NULL;
SELECT * FROM students WHERE gender IS NOT NULL;
SELECT * FROM students ORDER BY name DESC LIMIT 2;
SELECT * FROM students ORDER BY name DESC LIMIT 1,2;
SELECT * FROM students WHERE id >=2 and id <=4
SELECT * FROM students WHERE BETWEEN 2 AND 4
SELECT * FROM students WHERE name LIKE 't%'
SELECT * FROM students WHERE name RLIKE '.*[lo].*';
SELECT id stuid,name as stuname FROM students
select * from students where classid in (1,3,5);
select * from students where classid not in (1,3,5);
删除表
DROP TABLE [IF EXISTS] 'tbl_name';
修改表
ALTER TABLE ‘tbl_name’
#字段:
#添加字段:add
ADD col1 data_type [FIRST|AFTER col_name]
#删除字段:drop
#修改字段:
alter(默认值), change(字段名), modify(字段属性)
修改表范例
#修改表名
ALTER TABLE students RENAME s1;
#添加字段
ALTER TABLE s1 ADD phone varchar(11) AFTER name;
#修改字段类型
ALTER TABLE s1 MODIFY phone int;
#修改字段名称和类型
ALTER TABLE s1 CHANGE COLUMN phone mobile char(11);
#删除字段
ALTER TABLE s1 DROP COLUMN mobile;
#修改字符集
ALTER TABLE s1 character set utf8;
#修改数据类型和字符集
ALTER TABLE s1 change name name varchar(20) character set utf8;
#添加字段
ALTER TABLE students ADD gender ENUM('m','f');
alter table student modify is_del bool default false;
#修改字段名和类型
ALETR TABLE students CHANGE id sid int UNSIGNED NOT NULL PRIMARY KEY;
#删除字段
ALTER TABLE students DROP age;
#查看表结构
DESC students;
#新建表无主键,添加和删除主键
CREATE TABLE t1 SELECT * FROM students;
ALTER TABLE t1 add primary key (stuid);
ALTER TABLE t1 drop primary key ;
#添加外键
ALTER TABLE students add foreign key(TeacherID) references teachers(tid);
#删除外键
SHOW CREATE TABLE students #查看外键名
ALTER TABLE students drop foreign key <外键名>;
Adding a new column:
ALTER TABLE t1 ADD x INT;
Dropping a column:
ALTER TABLE t1 DROP x;
Modifying the type of a column:
ALTER TABLE t1 MODIFY x bigint unsigned;
Changing the name and type of a column:
ALTER TABLE t1 CHANGE a b bigint unsigned auto_increment;
Combining multiple clauses in a single ALTER TABLE
statement, separated by commas:
ALTER TABLE t1 DROP x, ADD x2 INT, CHANGE y y2 INT;
Changing the storage engine:
ALTER TABLE t1 ENGINE = InnoDB;
Rebuilding the table (the previous example will also rebuild
the table if it was already InnoDB):
ALTER TABLE t1 FORCE;
以上是关于MySQL表更改ALTER,CHANGE,MODIFY的区别的主要内容,如果未能解决你的问题,请参考以下文章
MySql 修改表结构时 ALTER,MODIFY,CHANGE的区别
MySql 修改表结构时 ALTER,MODIFY,CHANGE的区别