一、SQL语句
MySQL,Oracle,SQLServer,PostgreSQL都支持结构化查询语言去操作。
二、结构化查询语言分类
1.数据定义语言(DDL)
create drop alter
2.数据操纵语言(DML)
insert update delete
3.数据查询语言(DQL)
select where group by having order by
4.数据控制语言(DCL)
grant revoke
5.事务控制语言(TCL)
commit rollback
三、数据查询语言
1.select,where,and,or,
2.inner join,left join,right join,join,union,
3.limit,order by,group by,in, having,
4.between and,like,distinct,exists,as
5.sum,avg,count
-- 1、查询所有表数据
select * from sys_dept;
-- 2、带条件查询
select * from sys_dept where dept_id = 100;
-- 3、多条件查询
select * from sys_dept where dept_id = 100
and `status` = 1 and leader = '若依';
--
select * from sys_dept where dept_id = 100
or `status` = 1 or leader = '若依';
-- 4、 带条件查询,in 集合
select * from sys_dept
where dept_id in (101,102,103);
-- 5、带条件查询,带有范围查询
select * from sys_dept where dept_id between 100 and 105;
select * from sys_dept where create_time between '2023-11-01 00:00:00' and '2023-11-20 23:59:59';
-- 6、分组查询
-- count(*):对所有列进行统计。
-- count(1) 对第一列,主键列做统计。
select dept_name,count(*) from sys_dept group by dept_name;
-- 7、查询出部门由两条记录以上的记录
select dept_id,dept_name,count(1) from sys_dept group by dept_name,parent_id having count(1) > 1;
-- 8、排序:order by: 默认升序:asc,降序 desc
select * from sys_dept order by dept_id;
elect * from sys_dept order by dept_id asc;
select * from sys_dept order by dept_id desc;
-- 9、获取指定条数,limit
-- 获取表的前三条数据
select * from sys_dept limit 3;
-- 10、模糊查询,like
select * from sys_dept where dept_name like '%科技%';
-- 11、去重distinct
select distinct * from sys_dept;
-- 12、取别名 as
select dept_name as '部门' from sys_dept;
四、DQL查询进阶
1.连接查询
内连接(自然连接):
select * from a表 inner join b表 on a.id = b.number inner join c表 a.id = c.id
select * from a,b,c where a.id = b.number and a.id = c.id
外连接:左外连接,右外连接
select * from `user` a left join rule as b on a.rid = b.rid
2.合并查询
单表合并,多表合并
select * from t_user a
union
select * from t_user b
-- 要求返回的列数要一模一样
3.子查询
以查询结果作为筛选条件加入其他查询
写在where,from后面,还可以作为一个having条件
- 连接查询
select a.* from user a , rule b
where a.rid = b.rid
and
b.rname = '董事长'
-- 嵌套查询
select a.rid = (
select rid from rule where rname = "董事长"
)
select a.I from t_user a,(select * from t_role) b
where a.rid = b.rid