单表数据查询
简单查询
1、查询所有字段
语法格式:
select * from table_name
2、查询指定字段
语法格式:
select column_name1[, column_name2, ...] from table_name;
只要在 select
关键字后添加单个或多个字段名即可, 字段指定的顺序就是查询结果显示的顺序。
例如:
select deptno, job from emp;
3、去除重复记录的查询
语法格式:
select distinct column_name1[, column_name2, ...] from table_name;
当 distinct
关键字作用于多个字段时,只有多个字段的值都相同,重复记录才能被成功去除。
例如:
去除员工部门编号和工作职称的重复记录。
select distinct deptno, job from emp;
4、算术运算符
运算符类型 | 作用 |
---|---|
+ | 加法运算 |
- | 减法运算 |
* | 乘法运算 |
/ | 除法运算 |
% | 求余运算 |
例如:
使用算数运算符查询表中员工名和员工的年薪。
select ename, sal*12 from emp;
5、使用字段别名的查询
语法格式:
select column_name1 [as] othername1[, column_name2 [as] othername2], ... from table_name;
例如:
将员工的月薪工资修使用别名年薪工资查询。
select ename, job, sal*12 yearsal from emp;
对查询结果排序
按照指定的单字段排序
语法格式:
select column_name1[, column_name2], ... from table_name order by order_name[asc|desc];
column_name
表示要查询的字段名;order_name
表示按照该字段进行排序;asc|desc
表示升序和降序,默认按照升序排序。
例如:
按照表中员工的月薪来进行升序排序;
select ename, hiredate, sal from emp order by sal;
按照指定的多字段排序
语法格式:
select column_name1[, column_name2], ... from table_name order by order_name1[asc|desc], order_name2[asc|desc];
例如:
按照月薪 sal
字段的数据进行升序排序,如果该字段的值相同;则按照入职日期 diredate
字段的数据进行降序排序。
select ename, hiredate, sal from emp order by sal, hiredate desc;
条件查询
语法格式:
select column_name1[, column_name2], ... from table_name where where_condition;
比较运算符
运算符类型 | 作用 |
---|---|
> | 大于 |
< | 小于 |
>= | 大于等于 |
<= | 小于等于 |
= | 等于 |
<> | 不等于 |
!= | 不等于 |
-
>
查询大于18岁的信息
select * from table_name where age > 18;
-
<
查询小于18岁的信息
select * from table_name where age < 18;
-
=
查询年龄为18岁的信息
select * from table_name where age = 18;
判断运算符
查询类型 | 作用 |
---|---|
[not] between … and … | 判断某个字段的值是否在指定范围内 |
[not] in | 判断某个字段的值是否在某个指定的集合内 |
is [not] null | 判断某个字段的值是否为空 |
[not] like | 实现字符串的模糊查询 |
-
[not] between ... and ...
语法格式:
select column_name1[, column_name2], ... from table_name where column_name [not] between value1 and value2;
例如:
查询emp表中月薪在1500 到 3000之间的员工信息
select * from emp where sal between 1500 and 3000;
-
[not] in
语法格式:
select column_name1[, column_name2], ... from table_name where column_name [not] in (value1, value2, ...)
例如:
查询emp表中,员工姓名字段的值为 “Ward”、"Blake"的员工信息。
select * from emp where ename in ('Ward', 'Blake');
-
is [not] null
语法格式:
select column_name1[, column_name2], ... from table_name where column_name is [not] null;
例如:
查询emp表中,员工津贴
comn
字段的值为null
的员工信