1. CURD常用操作
![](https://img.php.cn/upload/image/226/782/879/1614249789744641.png)
-- 增
insert users (name,gender,salary,email,birthday)
values ('php','male',888,'php@php.cn','1993-08-03'),
('cn','male',888,'php@php.cn','1993-08-03');
-- 删
delete from users where name = 'cn';
-- 改 将users库中name值为php的改为helloworld
update users set name = 'helloworld' where name = 'php';
-- 查
select name,gender,email,salary from users where name = 'helloworld';
2. 常用select查询、关联查询
![](https://img.php.cn/upload/image/493/136/872/1614249807532715.png)
-- 条件查询:查询salary大于8000的用户
select sid,name,salary from users where salary>8000;
![](https://img.php.cn/upload/image/265/589/934/1614249814647506.png)
-- 区间查询:salary > 6000 salary <= 8000;
select sid,name,salary from users where salary > 6000 and salary <= 8000;
![](https://img.php.cn/upload/image/222/857/945/1614249824822375.png)
-- 分组查询:按性别分组查询,统计数量
select gender 性别, count(*) 数量 from users group by gender;
![](https://img.php.cn/upload/image/325/392/485/1614249834792816.png)
-- 排序查询:按年龄降序排序
select sid,name,age,salary from users order by age desc limit 5;
![](https://img.php.cn/upload/image/309/719/878/1614249841118952.png)
-- 分页查询:每页显示五条记录,查询第二页,偏移量公式:offset = (2-1) * 5 = 5
select sid,name,email from users limit 5 offset 5;
![](https://img.php.cn/upload/image/999/478/790/1614249854446426.png)
-- 集合查询:查询id为35,38,40
select sid,name,salary from users where sid in (35,38,40);
![](https://img.php.cn/upload/image/618/972/534/1614249865179367.png)
-- 模糊查询:查询名称第二个带o的用户
select sid,name,salary from users where name like '_o%';
![](https://img.php.cn/upload/image/792/305/186/1614249872505355.png)
-- 分组过滤查询:按性别分组查询,num统计数量,过滤条件为男性
select gender, count(*) num from users group by gender having gender = 'female';
关联查询
![](https://img.php.cn/upload/image/104/628/915/1614249880969802.png)
左外连接
![](https://img.php.cn/upload/image/373/470/816/1614249886186663.png)
-- 内连接使用join
select a.aid,title,name
from articles a join categories c
using(cid);
-- 关联查询
select a.aid,title,name from articles a, categories c where a.cid = c.cid;
-- 左外连接:左主表,右从表
select *
from articles a
left join categories c
on a.cid = c.cid;
-- 右外连接:右主表,左从表
select *
from articles a
right join categories c
on a.cid = c.cid;
3. mysql预处理原理
![](https://img.php.cn/upload/image/948/521/278/1614249894619347.png)
-- 生成预处理的sql语句
prepare stmt from 'select sid,name,salary from users where salary > ? limit ?';
-- 将真实的数据绑定到预处理语句的占位符
set @salary=5000, @num=2;
execute stmt using @salary, @num;