MySQL 表的增删改查
2022-07-03
创建表
# 查看创建数据表的 帮助
mysql> ? create table
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
....
# 创建数据表的语法
create table tb_name (
字段名 字段数据类型[(宽度) 约束条件],
字段名2 字段数据类型2[(宽度) 约束条件]
) 数据表的额外参数;
⚠️:同一张表中,
字段名不能相同;
宽度和约束条件可选;
字段名和类型是必须的;
# 完整创建语句
# 注意,mysql 默认关键字大小写不敏感,数据表是严格区分大小写的
# 字段名 数据类型 [额外的选项,可选]
# 引擎理解,好比汽车有不同种类的发动机,各种发动机有各种优缺点
CREATE TABLE IF NOT EXISTS `tanks`(
`id` INT,
`name` VARCHAR(100) NOT NULL,
`skills` VARCHAR(255) NOT NULL,
`price` int not null,
PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
# 插入信息
mysql> insert into tanks (id, name, skills, price) values(1, '程咬金','大招回血,血量越低,伤害越高',8888),(2,'大鱼庄周','免疫所有人友的负面控制·,2888);
查看表
# 查看表
mysql> show tables;
+-----------------+
| Tables_in_test1 |
+-----------------+
| tanks |
+-----------------+
1 row in set (0.00 sec)
# 查看创建表的信息
mysql> show create table tanks\G;
*************************** 1. row ***************************
Table: tanks
Create Table: CREATE TABLE `tanks` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`skills` varchar(255) NOT NULL,
`price` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
ERROR:
No query specified
# 查看表结构
desc table tanks;
修改表
示范
示例:
1, 修改存储引擎
alter table service engine=innodb;
2, 添加字段
alter table student10
add name varchar(20) not null,
add age int(3) not null default 22;
alter table student10
add stu_num varchar(10) not null after name; //添加在 name 字段之后
alter table student10
add sex enum('male', 'female') default 'male' first; //添加到最前面,二选一
3, 删除字段
alter table student10
drop sex;
alter table service
drop mac;
4, 修改字段类型 modify
alter table student10
modify age int(3);
alter table student10
modify id int(11) not null primary key auto_increment; //修改为主键,自增主键
5, 增加约束(针对已有的主键增加 auto_increment)
mysql> alter table student10 modify id int(11) not null primary key auto_increment;
ERROR 1068 (42000): Multiple primary key defined
mysql> alter table student10 modify id int(11) not null auto_increment;
Query OK,0 rows affected (0.01 sec)
Records:0 Duplicates:0 Warnings:0
6, 对已经存在的表增加复合主键
mysql> alter table service2
-> add primary key(host_ip, port);
7, 增加主键
mysql> alter table student1
-> modify name varchar(10) not null primary key;
8, 增加主键和自动增长
mysql> alter table student1
-> modify id int not null primary key auto_increment;
9, 删除主键
a,删除自增约束
mysql> alter table student10 modify id int(11) not null;
b,删除主键
mysql> alter table student10
-> drop primary key;
复制表
复制表结构+记录(key 不会复制:主键、外键和索引);因为查询
mysql> create table new_service select * from service;
只复制表结构
mysql> select * from service where 1=2; //条件为假,查不到任何记录,但是表结构有
Empty set (0.00 sec)
mysql> create table new1_service select * from service wher e 1=2; //条件为假,查不到任何记录,但是表结构被创建了
Query OK,0 rows affected (0.00 sec)
Records:0 Duplicates:0 Warnings:0
mysql> create table t4 like mysql.user; # 这种情况下表结构,主键、索引都会复制过来;但是不会拷贝数据过来
删除表
DROP TABLE 表名;