sql手写顺序:
select <select_list>
from <table_name>
<join_type> join <join_table> on <join_condition>
where <where_condition>
group by <group_by_list>
having <having_condition>
order by <order_by_condition>
limit <limt_number>
查询语句:
select 字段1,字段2... from 表名 where 查询条件
去重查询
select distinct 字段 from 表名 where 查询条件
修改语句:
update 表名 set 字段1=值, 字段2=值... where 字段=值
插入语句:
insert into 表名 values(值1,值2....) //不写插入的字段,则每个字段都要给值
删除语句:
delete from 表名 where 字段=值
常用的聚合函数:
平均值:select avg(字段) from 表
数量 count
select count(字段) from 表
返回不同的数目
select count(distinct 字段) from 表
排名第一的 first
select first(字段) from 表
选择最后的 last
select last(字段) from 表
最大值 max
select max(字段) from 表
最小值 min
select min(字段) from 表
求和 sum
select sum(字段) from 表
分组 group by
select * from 表 group by 字段
结果筛选 having 可以和聚合函数一起用,必须要跟group by一起使用
select * from 表
where
... group by 字段 having sum(字段) > 10
返回查询记录
select * from 表
where
exists(select * from 表)
多表查询:
多个where
select * from A where A.id = (select id from B where name='a');
联结查询:join
内联:取两个表的交集
![](https://img-blog.csdnimg.cn/bcc4f3f7f69647299a2662cd7ed6f1d6.png)
select 字段 from A inner join B on A.id=b.id
左联:左表有数据但是右表没有数据,此时左表数据也返回,右表字段为null
![](https://img-blog.csdnimg.cn/c0859da6fe0943f8b1413f9e49cdc2c5.png)
![](https://img-blog.csdnimg.cn/b2a4ed1bd90f4b0c8117b767b49cdb57.png)
select 字段 from A left join B on A.id=b.id
右联:右表有数据但是左表没有数据,此时右表数据也返回,左表字段为nul
![](https://img-blog.csdnimg.cn/3f7afc5b5a784121966d55eb3ab39c81.png)
![](https://img-blog.csdnimg.cn/32d1bf1858164d4c9e51c0d070fdfff9.png)
select 字段 from A right join B on A.id = B.id