MySQL 表的操作之查(select)和排序数据查询(order by)

260 阅读3分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第11天,点击查看活动详情

表中数据的操作 – 查(select)

1、单表数据查询

1.1简单数据查询

语法1:select f1,f2,f3,...from table_name;
语法2:select * from table_name;
 【说明:f1 f2表示表中的列名  *表示表中所有的列】
select * from t_employee;
select empno,ename,sal from t_employee;

1.2 distinct关键字 避免重复数据的查询

例子:查询员工表中职位(job列)列的所有数据

select job from t_employee;

例子:查询员工表中有哪些职位,使用distinct去重

select distinct job from t_employee;

1.3 可以使用四则运算进行数据查询(+ - * /)

例子1:查询员工表中所有员工的工资

select sal from t_employee;

例子2:查询员工表中所有员工的年薪

select sal,sal*12 from t_employee;

1.4 给列起别名

语法:select f1 [as] 别名,f2 [as] 别名...
        from table_name;
  说明:as可以省略

例子:查询员工表中所有员工的月薪和年薪

select sal as monthsal,sal*12 as yearsal from t_employee;
select sal monthsal,sal*12 yearsal from t_employee;

1.5 concat关键字-设置显示格式的数据查询

例子:查询员工表中每位员工的年薪,显示格式要求:xx的年薪为xx

select ename,sal*12 from t_employee;
select concat(ename,sal*12) from t_employee;
select concat(ename,'的年薪为',sal*12) yealsal
     from t_employee;

练习:查询员工表中的数据,显示结果为: 我是 xx ,我的入职日期是 xx 号

select concat('我是',ename,',我的入职日期是'
     ,Hiredate,'号') as message
     from t_employee;

排序数据查询

order by 对查询结果排序 默认asc(升序),desc(降序)

默认情况下查询出的数据顺序是按照插入的顺序来查询。 可以使用order by来设置数据的查询顺序。

 语法:select f1,f2,f3,....
        from table_name
        where 条件
        order by f asc/desc;

说明:f表示按照哪列进行排序 asc表示升序,asc可以省略,默认是升序排列 desc表示降序,desc必须写

a 单字段排序

例子1:查询员工表中所有的员工,同时按照工资对查询结果进行升序排列。

select empno,ename,sal 
    from t_employee
    order by sal;

或者

select empno,ename,sal 
    from t_employee
    order by sal asc;

例子2:查询员工表中所有的员工,同时按照工资对查询结果进行降序排列。

select empno,ename,sal 
    from t_employee
    order by sal desc;

例子3:查询员工表中工资大于2000的员工,同时按照工资降序排列。

select empno,ename,sal,Hiredate
     from t_employee
     where sal>2000
     order by sal desc;

在这里插入图片描述

b 多字段排序

例子1:查询员工表中所有的员工,按照工资升序,入职日期降序进行数据查询。

select ename,sal,Hiredate
    from t_employee
    order by sal asc,Hiredate desc;

作业:查询员工表中在部门10和20的员工,同时按照工资降序查询。

select ename,sal,deptno
    from t_employee
    where deptno in(10,20)
    order by sal desc;

或者

select ename,sal,deptno
    from t_employee
    where deptno=10 or deptno=20
    order by sal desc;

先按照sal 升序排序,再按照Hiredate 降序排序; 在这里插入图片描述