目录
⼀、⾼级
1.1 ⼦查询
- ⼦查询嵌⼊到其他查询语句中查询语句,⼦查询只能出现在from, where、having中
- ⼦查询不要⽤select *,exists除外
select title from forum where uid in (select id from php_user where name = '王坤');
select * from blog_article where cid in(select cid from blog_category where name='心情');
select * from (select uid,username,gender from blog_user where gender='男') as user;
1.2 多表查询
- 多表连接必须要有连接条件,否则结果没有意义
- 多表连接有两种写法:隐式(标准sql)和显式内连接
- 隐式(标准sql)连接 : 连接条件写到where字句中
select title,content,name,publish_time
-> from user u,forum f #给表起⼀个别名,⽅便书写
-> where u.id = f.uid; 在where写链接条件
select title,content,name,publish_time
-> from user u,forum f
-> where u.id = f.uid and name='王琨';
select a.username,b.name ,c.title
-> from bbs_user a,bbs_category b,bbs_forum c
-> where b.cid = c.cid and c.uid = a.uid;
- 显示内连接(inner join)
- 表的⾃身连接
select * from areainfo a,areainfo b where a.pid= b.code and a.name='青河县';
1.3 外连接
两张表关联查询时,根据以那种表为主可以分为左外连接和右外连接
- 左外连接
以左表为主,如果右边的表⾥没有匹配的记录,则添加⼀个万能记录(各个字段都为null)与之连接
- 右外连接(right join)
以右表为主,如果左边的表里没有匹配记录,则增加一个万能记录与之连接
1.4 集合操作
可以使⽤union将两个查询结果合并, mysql只⽀持并,不⽀持差和交
- 两个结果集中字段数⼀样,对应字段类型兼容
- ⾃动去除重复记录,不去除重复记录可以⽤ union all
- order by 放到最后
1.5 内部函数
- 字符串函数
- ⽇期函数
select DATE_FORMAT(now(),'%Y- %m-%d %H:%i:%s');
- 数学函数
- 其它函数
⼆、数据控制
2.1 事务
- 事务把⼀组操作看做⼀个整体,要不都操作成功,要不都操作失败 。 (ACID)
- 表的数据库引擎必须是innodb, innodb⽀持事物, myisam不⽀持事务
- 修改表引擎: alter table 表名 engine = innodb
-- 查询是否为⾃动提交
select @@autocommit #(1为⾃动提交 0为⼿动提交)
-- 关闭⾃动提交
set autocommit = 0
start transaction /begin
-- ⼀组操作
commit/rollback
commit #提交 会把数据写到硬盘
rollback #回滚 撤销操作 撤销从begin到这一条命令之间的操作
2.2 授权管理
- 创建⽤户
create user '⽤户名'@'服务器地址' identified by '密码'
- 删除⽤户
drop user '⽤户名'@'服务器地址'
修改密码
- 刷新
flush privileges