MYSQL表操作的常用指令

select 字段 from 表名
select 字段 列的别名 from 表名
distinct:去除别名 select distinct 字段
describe / desc:显示表结构 desc 表名
过滤数据:select 字段 from 表名 where 过滤条件
运算符: + - * / %或mod select a+b
比较运算符: =(如果等号两边有一个null,结果为null) <=>(安全等于:两边都是null 返回1,一个为null 返回0) < <= > >= !=/<>
is null:为空 is not null:不为空 select 字段 from 表名 where 条件 is null
in:在列表里: select 字段 from 表名 where 条件 in (条件列表)
like:匹配字符:select 字段 from 表名 where 条件 like ‘%a%’ %匹配多个字符 _匹配一个字符
逻辑运算符:not或! and或&& or或|| xor异或
order by(排序): select 字段 from 表名 order by 字段 ASC(升序-默认)/DESC(降序)
多列排序 select 字段 from 表名 order by 字段1, 字段2 (第一列相同根据第二列进行排序)
limit(分页): select 字段 from 表名 limit 起始位置, 每页显示行数 公式:(当前页数-1)*每页条数,每页条数 注意:limit必须放在整个select语句最后
查询分类:等值连接vs非等值连接
自连接vs非自连接
内连接vs外连接 SQL99语法中 左(右)外连接 select 字段 from A表 left(right) outer join B表 on 条件 where 其他条件
满外连接: left outer join … UNION right outer join …
union(合并查询结果): select 字段 from 表名 union select 字段 from 表名
union和union all区别:union返回两个查询结果集的并集, 去除重复记录, union all返回两个查询结果集的并集, 不去重 (union all执行时的资源比union少)
日期函数:
返回当前日期,只包含年月日: curdate() crrrent_date()
返回当前时间,只包含时分秒: curtime() current_time()
返回当前系统日期和时间: now()
流程控制函数:
if(value,value1,value2) 如果value值为true,返回value1,否则返回value2
ifnull(value1,value2) 如果value1不为null,返回value1,否则返回value2
case when 条件1 then 结果1 when 条件2 then 结果2…else resultn end 相当于java的if…else if…else
聚合函数(不能嵌套使用
avg()平均 sum()求和 max()最大 min()最小 count()返回表中记录总数
group by(分组): select 字段 from 表名 where 条件 group by 字段 注意:在select中未包含在聚合函数的列都应该包含在group by子句中
having(过滤分组):select 字段 from 表名 group by 字段 having 条件 注意:where中不能使用聚合函数作为条件,having中可以使用聚合函数作为条件,having必须和group by一起使用
多行子查询比较符
in 等于子查询返回列表中的任意一个
any 需要和单行比较符一起使用 和子查询返回的某一个值比较 select 字段 from 表名 where 字段 > any(子查询)
all 需要和单行比较符一起使用 和子查询返回的所有值进行比较 select 字段 from 表名 where 字段 > all(子查询)
some 是any的别名
除了group by和limit都可以使用子查询
创建数据库:create database if not exists 数据库名
查看当前所有数据库:show databases
查看当前正在使用的数据库:select database()
查看指定库下所有的表:show tables from 数据库名
查看数据库的创建信息:show create database 数据库名
使用/切换数据库:use 数据库名
修改数据库:alter database 数据库名 character set 字符集; 如gbk utf8
删除数据库:
方式1:drop database 数据库名 方式2:drop database if exists 数据库名
创建表:
方式1: create table 表名(
字段1, 数据类型,
字段2, 数据类型,
字段3, 数据类型);
方式2: create table 表名 as select查询;
查看表名:show create table 表名
修改表:
追加一列: alter table 表名 add 字段 字段类型
在指定位置添加:alter table 表名 add 字段 字段类型(first/after 字段)
修改一列: later table 表名 modify 字段 字段类型
在指定位置添加:alter table 表名 modify 字段 字段类型(first/after 字段)
重命名一个列:alter table 表名 change 列名 新列名 新数据类型
删除一个列:alter table 表名 drop 字段名
重命名一个表:rename table 表名 to 新表名
删除表:drop table 表名1; 不能回滚
清空表:truncate table 表名; 清空表中所有数据 不能回滚 使用delete可以回滚
数据的增删改:
插入数据:insert into 表名 values (value1, value2);
为表的指定字段插入数据:insert into 表名 (字段1, 字段2) values (value1, value2);
同时插入多条数据:insert into 表名 values (value1, value2),(value1, value2);
将查询结果插入表中:insert into 表名 (字段) select (字段) from 源表名 where 条件
更新数据:update 表名 set 要更新的数据 where 条件
删除数据:delete from 表名 where 条件 如果省略where子句,则表中的全部数据将被删除


版权声明:本文为qq_40577814原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。