DQL操作
SELECT 列名称 FROM 表名称
1.基本查询
Select * from A a ;
-- 别名(as可以省略)
Select a.str1 as user_name from A a;
-- where子句
-- and or
语法:SELECT 列名称 FROM 表名称 WHERE 列 运算符 值
-- 精确查询
Select * from A a where 1=1 and a.str1 = ’test’;
-- 模糊查询
Select * from A a where 1=1 and a.str1 like ’%test%’;
备注:% 替代一个或多个字符
_ 仅替代一个字符
-- 排序 order by
desc(倒序) asc(顺序[默认])
select * from A a order by a.str1 ;
常见聚合函数
sum( )[求和] ,avg( )[求平均值] ,max( )[求最大值] ,min( )[求最小值] ,count( )[计数]
select sum(a.num1) from A a;
select a.str1 from A a group by a.str1 ;
select a.str1,sum(a.num1) from A a group by a.str1 ;
--分组
Select a.str1 from A a group by a.str1;
--having 过滤聚合函数
Select a.str1 from A a group by a.str1 having count(1)>10;
-- SELECT DISTINCT(DISTINCT 用于返回唯一不同的值)
语法:SELECT 列名称 FROM 表名称
Select distinct a.str1 from A a ;
-- case表达式
简单Case函数
CASE sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE '其他' END
Case搜索函数
CASE WHEN sex = '1' THEN '男'
WHEN sex = '2' THEN '女'
ELSE '其他' END
【拓展】like 多条件匹配
Select * from A a where 1=1 and REGEXP_LIKE(字段名, '(匹配串1|匹配串2|...)');
【备注】
and REGEXP_LIKE(字段名, '(匹配串1|匹配串2|...)') //全模糊匹配
and REGEXP_LIKE(字段名, '^(匹配串1|匹配串2|...)') ";//右模糊匹配
and REGEXP_LIKE(字段名, '(匹配串1|匹配串2|...)$') ";//左模糊匹配
- 连接查询
等值连接 和 不等值连接
等值连接就是连接条件中使用"="连接两个表,而不等值连接就是指连接条件中使用> >= < <= != <> between ... and... 等。
--1.等值连接查询
select a.*,b.* from A a , B b where a.str1=b.str1;
--2.不等值连接
select a.*,b.* from A a , B b where and.str1 between b.str1 and s.str2;
--内连接 inner join
Select a.*,b.* from A a inner join B b on a.str1=b.str1 ;
--外连接 left join ,left jion ,full join
select a.* ,b.str1 from A a left join B b on a.str1=b.str1 ;
select a.* ,b.str1 from A a right join B b on a.str1=b.str1 ;
select a.* ,b.str1 from A a full join B b on a.str1=b.str1 ;
【例子】
inner join
left join
right join
full join
--子查询
select a.* from A a where a.str1=(select b.str1 from B b where b.str3='test')
select a.* from A a where (a.str1,a.str2)=(select b.str1,b.str2 from B b where b.str3='test')
--找出A中字段str1,大于B表字段str1且在B表满足str2=’test’的数据
select a.* from A a where a.str1> any (select b.str1 from B b where b.str2='test')
--找出A中字段str1,大于任何B表字段str1且在B表满足str2=’test’的数据
select a.* from A a where a.str1> all (select b.str1 from B b where b.str2='test')
--in和exists
Select * from A a where 1=1 and a.str1 in (‘test1’,test2’);
--exists 指定一个子查询,检测 行 的存在
Select * from A a where 1=1 and exists(select 1 from B b where b.str1=a.str1 );
【区别】:
in 和 exists的区别:
如果子查询得出的结果集记录较少,主查询中的表较大且又有索引时应该用in, 反之如果外层的主查询记录较少,子查询中的表大,又有索引时使用exists;
not in 和 not exists的区别:
如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists都比not in要快。