1.库操作
登录数据库(-h -u -p -P都不需要空格)
mysql -h {ip} -u {username} -p{password} -P {port}
# -h ip默认是 localhost
# -p 指定密码时中间不要空格,比如 -p123456
# -P 端口默认是 3306
1.1 增
create database 库名
1.2 删
drop database 库名
1.3 查
show databses
1.4 用
use 库名
2.表操作
2.1 增
create table 表名( 列名 类型 约束 )
eg
CREATE TABLE IF NOT EXISTS `runoob_tbl`(`runoob_id` INT UNSIGNED AUTO_INCREMENT,`runoob_title` VARCHAR(100) NOT NULL,`runoob_author` VARCHAR(40) NOT NULL,`submission_date` DATE,PRIMARY KEY ( `runoob_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.2 删
drop table 表名
2.3 改
2.3.1 表重命名
rename table 旧名 to 新名
2.3.2 列操作
Alter table 表名 add 列名 烈性 约束 // 新增
Alter table 表名 drop // 删除
Alter table 表名 change 旧名 新名 // 重命名
Alter table 表名 modify 列名 类型 约束 // 列类型修改
2.4 查
show tables
3.数据操作
3.1 insert
insert into 表(列,列)values ( , )
- 增主键
3.2 delete
delete from 表 where ...
3.3 update
update 表 set 列=值 where ...
3.4 select
3.4.1 基本查询
select 列 from 表 where ...
1.where条件
-
逻辑运算符:and / or / not
-
关系运算符:= / <= / >= 或者 in( , ) / between … and …
-
模糊查询:like("%…%")
-
isNull等
2.其余条件
select (distinct) 列(+n) (as别名) from 表(as别名) where ... (order by 列 ASC/DESC)
3.聚合函数
select count(列)/sum(列)/max(列)/min(列)/arg(列) from 表 (group by(列)) (having) ...
group by : 将相同的分为一组(一行数据),常配合聚合函数使用
where与having的区别?
where 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据。where条件中不能包含聚合函数,可以使用where条件过滤出特定的行。
Having字句与where子句一样可以进行条件判断的,另外Having子句通常用来筛选满足条件的组,即在分组之后过滤数据。条件中经常包含聚合函数,使用having条件过滤出特定的组,也可以使用多个分组标准进行分组。
通常使用group by+having的时候会使用聚合函数,因为分组之后的列要么是聚合函数,要么是group by(列)中的列。
3.4.2 分页查询
select 列 from 表 limit (page-1)*n,n
3.4.3 联合查询
select 列 from 表1 ~join 表2 on 表1.字段= 表2.字段
- inner join : 内联,返回左右表联结字段都非空的行
- left join:左联,返回左表所有与右表联结字段非空的行
- right join:右联,返回右表所有与左表联结字段非空的行
3.4.4 子查询
select * from (select 列 from 表1 where ...)
3.4.5 并查询
select 相同列名 from 表1 union select 同列名 from 表2
注:union默认去重,union all允许重复