目录
1.登录命令
mysql -uroot -p
2.操作数据库命令
2.1查询数据库(show)
show databases;
2.2 创建数据库(create)
create database [if not exists] a1[数据库名称];
if not exists可以省略,一般用于防止数据库重名
2.3使用数据库(use)
use [数据库名称] a1(以表名称为a1为例);
3.操作表命令
3.1增加表
- 创建表(create)
create table students[表名](
id [名称] int[类型],
name varchar(60)[变长字符串类型(名称最大长度(单位字节))],
gender char(2),
english int,
chinese int,
math int
);
- 向表中插入数据(insert to)to可以省略
(1)全列插入
insert [to] students values ('1','张三','男','85','58','90');
(2)选择插入
insert [to] students (id,name) values ('2','李四');
(3)多行插入
insert [to] students values ('3','王五','女','55','58','70'),
('4','赵六','男','65','88','50'),('5','田七','女','45','28','70');
3.2查询表
- 显示数据库内所有表名称(show)
show tables;
- 显示表的格式(desc)
desc students[表名];
- 查询表中的所有内容(select)
select * from students[表名];
- 查询指定内容
select name,gender,math from students;
- 查询数学成绩及格的人(where)
select *from students where math>60;
- 查询语文成绩在50以上且姓王的同学(like)
select * from students where chinese>50 and name like '王%';
3.3修改表(alert)
- 基本命令
-- 添加新列
alert table 表名 add 列名 数据类型;
-- 删除列
alert table 表名 drop COLUMN 列名;
-- 修改列的数据类型
alert table 表名 MODIFY 列名 新数据类型;
-- 重命名列
alert table 表名 CHANGE 旧列名 新列名 数据类型;
-- 添加主键
alert table 表名 add PRIMARY KEY (列名);
-- 删除主键
alert table 表名 drop PRIMARY KEY;
-- 添加外键
alert table 表名 add CONSTRAINT 外键名 FOREIGN KEY (列名) REFERENCES 另一表名(列名);
-- 删除外键
alert table 表名 drop FOREIGN KEY 外键名;
- 修改表名(rename)
rename table 旧表名 to 新表名;
3.4 删除(delete/drop)
- 删除整个表(drop)
drop table [if exists] students[表名];
- 删除表中的内容(delete)
delete from students [表名] where id=1[条件];
删除前
删除后