SQL语句中的数据类型可以参考:http://blog.csdn.net/anxpp/article/details/51284106
本博文主要提供快速语法查询,后期会推出含有示例的篇章
打开/退出 MySQL
# 在win 或Linux 的命令行中,使用
mysql -u root -p(密码可写可不写,不写)
exit
quit
ctrl+d(linux)/ctrl+z(win)
select查看版本,显示当前时间,显示当前使用数据库
select version(); # 查看版本
select now(); # 显示系统当前时间
select database(); # 显示当前使用的数据库
使用数据库
use 数据库名;
查看所有数据库/表/
show databases; # 注意复数
show tables; # 查看数据库中所有的表以及视图 复数
show create table 表名; # 查看表的创建过程
创建数据库/表/视图
create database 数据库名 charset=utf8;
# ???如果忘记charset怎么处理?删除重新新建? 重新设置utf8很繁琐,现阶段删除重建
create table 表名(字段1 约束, 字段2 约束,字段3 约束...);
create view 视图名 as select ....;
create index 索引名 on 表名(字段名(长度));
删除数据库/表/视图
drop database 数据库名;
drop table 表名;
drop view 视图;
drop index
查看表结构
desc 表名;
修改表的字段名/结构
alter table 表名 add 字段名 约束; # 添加字段
alter table 表名 change 原字段名 新字段名 类型约束;
alter table 表名 modify 字段名 新约束;
alter table 表名 drop 字段名;
【增删改查】
查询所有列/指定列
select * from 表名;
select id, name from students; # id name 次序可调换
select id as 学号, name as 姓名 from students;
增
insert into 表名 values(...)
# 部分列插入
insert into 表名(字段*,...) values(值*,...)
# 多列同时插入 一行命令插入多条记录
insert into 表名 values(...),(...)...;
insert into 表名(字段*, ...) values(值*, ...),(值*, ...),...;
修改 记录
update 表名 set 列1=值1, 列2=值2... where 条件
删除 记录(建议使用逻辑删除)
delete from 表名 where 条件
update 表名 set is_delete = 1 where 条件
数据类型
# 数值:tinyint smallint mediumint int bigint decimal
# 字符串:char varchar text
# 日期时间:date time datetime year timestamp
# 枚举:enum
约束
primary key
not null
unique
default
foreign key
auto_increment
消除重复行
select distinct 列1,... from 表名;
【条件】
where
比较运算符
= != >= <= > <
逻辑运算符
and or not
模糊查询
like % _
rlike
# 以“李”开头匹配, 以'李'结尾匹配,中间包含'李'
like '李%'
like '%李'
like '%李%'
范围查询
in not in
between...and not between...and
空判断
null is null
排序
asc desc order by
select * from 表名 order by 列1 asc|desc [,列2 asc|desc,...]
聚合函数
round() round(avg(), 小数位数) # 四舍五入,保留指定位数的小数
count(*) # 计算总行数
max() # 最大值
min() # 最小值
avg() # 平均值
sum() # 总和
select count(*), max(列名), min(列名), avg(列名), sum(列名) from students where ...;
分组
group by # 可1个字段或多个字段
group_concat() # 分组字段值的集合
group by...having # having只能与group by结合使用
group by...with rollup # 在最后一行添加记录,记录总和
select 列名, group_concat(列名) from 表名 group by 列名;
获取部分行
select * from 表名 limit start, count; # start开始, count计数
连接查询
select * from 表名1 inner / left / right join 表名2 on 表1.列 = 表2.列
select * from 表名1 as 别名1 inner / left / right join 表名2 as 别名2 on 别名1.列 = 别名2.列
自关联
select * from 表名1 as 别名1 inner / left / right join 表名1 as 别名2 on 别名1.列1 = 别名2.列2
子查询
select * from 表名1 where 列名1 = (select 列名2 from 表名2 where ...);
MySQL完整格式
SELECT select_expr [,select_expr,...] [
FROM tb_name
[WHERE 条件判断]
[GROUP BY {col_name | postion} [ASC | DESC], ...]
[HAVING WHERE 条件判断]
[ORDER BY {col_name|expr|postion} [ASC | DESC], ...]
[ LIMIT {[offset,]rowcount | row_count OFFSET offset}]
]