第五章数据查询
数据查询
单表查询
l 一般形式:
select *(列名) from 表名 where 条件;
l 查询结果改列名:
select 列名 as 别名,列名 as 别名 from 表名 where 条件;
l 查询结果修改本列值:
Select 列名,列名 as 别名, case语句 from 表名;
例子:select name, id as ‘学号’,
Case
When score is null then ‘无’
When score >=80 then ‘优秀’
When score <80 and score>=70 then ‘良好’
When score <70 and score>=60 then ‘及格’
Else ‘不及格’
End as ‘成绩’ from 表名
l 查询结果消除重复:
Select distinct 列名,列名 from 表名 where 条件
l Where 子句
[列名=值]:>、=、<、>=、<=、!=
[列名 like ‘%模糊%’]:’_’单个字符、’%’模糊
[列名 in (‘值1’, ‘值2’, ‘值3’)]:多选1
[列名 between 值1 and 值2]:从‘值1’到‘值2’之间
And 、Or 逻辑链接
多表查询
l 内连接:两个表行数相等
Select * from 表1 inner join 表2 where 条件
例子
Select * from st inner join ad where st.id=ad.id
|
Id |
Name |
|
Id |
Score |
|
1 |
神雕 |
|
1 |
12 |
|
2 |
方式 |
|
2 |
34 |
|
3 |
阿达 |
|
3 |
54 |
l 外连接:左(右)表满足条件行数全存在
Select * from 表1 left[right] outer join 表2 on 条件
例子:
Select * from st left outer join ad on st.id=ad.id;
|
Id |
name |
Id |
Score |
|
1 |
神雕 |
1 |
12 |
|
2 |
方式 |
2 |
34 |
|
3 |
阿达 |
3 |
54 |
|
4 |
是的 |
Null |
Null |
l 子查询
[where 列名 in (子查询)]:查询符合子查询记录
[where 列名 >all]:比较子查询
All:大于全部 any|some:大于其中一个
l Group by子句:根据字段分组
From 表名 group by 列名 [asc|desc]
l Order by 子句:排序
Order by 列名 [asc|desc]

浙公网安备 33010602011771号