12、条件查询和排序

学习目标:

1、熟练掌握select语句的条件查询

2、掌握Order By语法

学习过程:

前面的查询都比较简单,都是查询全部的内容的,但是在现实生活中我们经常会需要查询符合一些条件的数据,而不是每一次都是全部数据。比如如果我们只需要查询工资在3000至5000之间员工,部门1的员工等等。这样我们可以在基本的查询语句后面通过where关键字添加查询条件即可。基本格式如下:

select * from table [where conditions]

1、比较条件

可以使用的比较符合是等于=、大于>、小于

1

2

3

4

--查询姓名等于zhangsan的员工

select * from employee where employee_name='zhangsan'

--查询工资大于3000的员工。

select * from employee where salary >3000

2、其它比较运算符

BETWEEN  num1 AND num2  介于num1和num2之间

IN(set)  在一列数据中。

LIKE     模糊匹配

IS NULL  判断是否是一个null值

Between two values (inclusive),  

示例代码如下:

1

2

3

  -- is null 

-- is not null 

select employee_name,salary, dep_id from employee where salary is not null

1

2

 --工资在10005000之间

select * from employee where salary between 1000 and 5000

-- 查询工资是1000,2000,3000的员工

select employee_name,salary, dep_id from employee where salary in(1000,2000,3000)

-- 查询工资不是1000,2000,3000的员工

select employee_name,salary, dep_id from employee where salary not in(1000,2000,3000)

这里重点讲讲like模糊查询,这里我们知道两个特殊的符号。% 表示任意长字符

_ 表示一个字符

1

2

3

4

 --如查询姓刘的所有的员工

select employee_name,salary, dep_id from employee where employee_name like '刘%'

--如查询姓名只有两个字,而且是姓刘的员工

select employee_name,salary, dep_id from employee where employee_name like '刘_'

3、逻辑条件

AND:如果组合的条件都是TRUE,返回TRUE

OR:如果组合的条件之一是TRUE,返回TRUE

NOT:如果下面的条件是FALSE,返回TRUE

上面的判断使用和java类似。如下面这个例子

1

2

--查询姓刘,并且工资大于5000的员工。

select * from employee where employee_name like '刘%' and salary>5000)

4、优先级

运算级默认从高到低的排列,当然其实也可以使用小括号改变运算的优先级别:

  1. 算术运算符

  2. 连接运算符

  3. 比较运算符

  4. IS [NOT] NULL, LIKE, [NOT] IN

  5. [NOT] BETWEEN

  6. NOT 逻辑条件

  7. AND逻辑条件

  8. OR逻辑条件

5、排序order by

使用ORDER BY 子句将记录排序

ASC: 升序,从小到大 默认

DESC: 降序,从大到小

ORDER BY 子局在SELECT指令的最后

select * from table [where conditions] [order by column1 asc|desc,column2 asc|desc]

如下面这个例子

1

2

3

4

--按照工资大降序排列,也就是工资从高到低的排列

select employee_name,salary as 工资, dep_id from employee order by  salary desc

--先按照工资降序排列,如果工资相等就按照员工的id升序排列

 select * from employee order by salary desc,employee_id asc

和where语句一起使用

select employee_name, dep_id from employee

         where salary  in(1000,2000,3000)

                order by salary desc

猜你喜欢

转载自blog.csdn.net/liubao616311/article/details/83957126