目录
数据库操作:
链接数据库
- cd 进入bin目录 输入 mysql -u root -p 然后输入密码
操作
- show databases; 显示数据库
- use 库名; 选择数据库
- DROP DATABASE 库名; 删除库
- creat database 库名; 创建库
表操作:
- show tables; 显示表
- drop table 表名; 删除表
- creat table 表名(
列名 类型 是否可以为空,
列名 类型 是否可以为空,
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
字段操作:
-
alter table 表名
add column `字段名` <数据类型> comment `备注`; 添加字段
-
alter table 表名
change column `老字段名` `新字段名` <数据类型> comment `备注`; 修改字段 -
alter table 表名
drop column 表名; 删除字段
记录操作:
增:
一次插入一条
- insert into `表名` set `字段名1` = ‘value1’ ,`字段名2` = ‘value2’
一次插入多条
- insert into `表名` ( `字段名1`, `字段名2`) values ( value1.1,value1.2 ),(value2.1,value2.2 )
根据索引值进行判断,若存在,先删除在插入
- replace into `表名` set `字段名1` = ‘value1’ ,`字段名2` = ‘value2’
删:
删除一条或多条
- delete from 表名 where id = (=也可以换成>,<)
(id号还是会继续累加)
初始化表
- truncate 表名
(id号从1开始)
改:
- update 表名 set 字段名1 = ‘value1’ ,字段名2 = ‘value2’ where id =
查:
单表查询
查询表中某些字段
- select 字段1,字段2 from 表
以表中某些字段为条件查询
- select * from 表 where 字段1=‘value1’ and 字段2=‘value2’
若查看除某些字段以外的其他: - select * from 表 where 字段 not in (‘value1’,‘value2’)
- select * from 表 where 字段 <> ‘value’
按照id号查询
1.select * from 表 where id =1or id=2 or id=3
2.select * from 表 where id in(1,2,3)
3.select * from 表 where id in(‘1’,‘2’,‘3’)
若查看除某些id号以外的其他:
- select * from 表 where id not in(‘1’,‘2’,‘3’)
排序
- select * from 表 order by 字段 desc(降) asc(胜) limit 0,3
(limit 0,3 从第一个开始选 选三个)
多表查询
子查询
场景:有两个表 员工信息employee_info ,员工工资employ_pay
我们需要根据一个人的姓名对应的id,查询对应的工资以及显示对应的姓名
- select pay,(select name from employ_info where id=3) as username from employ_pay where nameid=3
关联查询
- select b.name,a.pay from employ_pay a,employee_info b where a.nameid=b.id and b.id=3
左/右链接查询
- 左链接查询
(显示左边表所有记录,以及右边表满足条件的记录)
select a.*,b.pay from employee_info a left join employee_pay b on a.id=b.nameid - 右链接查询
(显示右边表所有记录,以及左边表满足条件的记录)
select a.*,b.pay from employee_pay a left join employee_info b on a.id=b.nameid
联合查询
- 查询语句1
union
查询语句2 - 条件:
1、要求多条查询 语句的查询列数是一致的
2、要求多条查询语句的查询的每一列的类型和最好一致
3、union关键字默认去重,如果使用union all 可以包含重复项