Mysql 关键字的使用【总结】

1、is nullis not null

  • 例:查询emp表中没有上级领导mgr的员工编号empno、姓名ename、工资sal:
    select empno,ename,sal from emp where mgr is null;
  • 例:查询emp表中没有奖金comm的员工姓名,工资,奖金:
    select ename,sal,comm from emp where comm is null;
  • 例:查询有奖金的所有员工信息:
    select * from emp where comm is not null;

2、别名:as省略

  • 例:将查询到的员工姓名ename改成’姓名’:
    select ename as 姓名 from emp;
    select ename 姓名 from emp;

3、去重:distinct

  • 例:查询emp表中出现的所有职位job:
    select distinct job from emp;

4、比较运算符:>、<、>=、<=、=、!=、<>

  • 例:查询工资小于等于1600的所有员工的姓名和工资:
    select ename,sal from emp where sal <= 1600;
  • 例:查询部门标号是20的所有员工姓名、职位和部门编号deptno:
    select ename,job,deptno from emp where deptno = 20;
  • 例:查询部门不是10号部门的所有员工姓名和部门编号:(两种写法)
    select ename,deptno from emp where deptno != 10;
    select ename,deptno from emp where deptno <> 10;

5、andorand等效于java中的&&or等效于java中的||

  • 例:查询工资大于2000并且是10号部门的员工信息:
    select * from emp where sal > 2000 and deptno = 10;
  • 例:查询部分是30号部门或者上级领导mgr为7698的员工姓名、职位,上级领导和部门编号:
    select ename,job,mgr,deptno from emp where deptno = 30 or mgr = 7698;

6、in

  • 例:查询emp表中工资是5000,1500,3000的员工信息:
    select * from emp where sal = 1500 or sal = 5000 or sal = 3000;
    select * from emp where sal in(1500,5000,3000);

7、between x and y(包含x和y):

  • 例:查询工资在2000到3000之间的员工姓名和工资:
    select ename,sal from emp where sal >= 2000 and sal <= 3000;
    select ename,sal from emp where sal between 2000 and 3000;

8、模糊查询:like

  1. _:代表单个未知字符
  2. %:代表0或多个未知字符
  • 例:以a开头的字符串:a%
  • 例:以m结尾:%m
  • 例:包含x:%x%
  • 例:第二个字符是a:_a
  • 例:倒数第三个字母是m:%m__
  • 例:以a开头并且倒数第二个字母是b:a%b_
  • 案例:查询名字中包含a的所有员工姓名和工资:
    select ename,sal from emp where ename like '%a%';
  • 案例:查询单价低于100的记事本(title包含记事本):
    select * from t_item where price < 100 and title like '%记事本%';
  • 案例:查询有图片image的得力商品信息:
    select * from t_item where title like '%得力%' and image is not null;
  • 案例:查询和得力无关的商品信息:(title不包含得力):
    select * from t_item where title not like '%得力%';

9、排序:order by关键字:

by后面写排序的字符名称(默认是升序):asc:升序,desc:降序

  • 例:查询所有员工的姓名和工资按照工资升序排序:
    select ename,sal from emp order by sal;
  • 例:查询10号部门所有员工的信息,按照工资降序排序:
    select * from emp where deptno = 10 order by sal desc;
  • 例:查询所有员工按照部门升序排序,如果部门一致则按照工资降序排序:
    select * from emp order by deptno,sal desc;
  • 例:查询所有商品分类和单价按照分类降序排序,如果分类相同则按照单价降序排序:
    select category_id,price from t_item order by category_id desc,price;

10、分页查询:limit

limit 跳过的条数,请求的数量(每页的数量)

  • 例:查询员工表中工资降序的前五条数据:
    select * from emp order by sal desc limit 0,5;
  • 例:查询员工表中工资降序的第3页的4条数据:
    select * from emp order by sal desc limit 8,4;
  • 例:查询商品表中价格低于100元的商品信息第三页的第三条数据
    select * from t_item where price < 100 order by price desc limit 6,3;
  • 例:查询10号和30号部门的员工工资在前三名的员工信息:
    select * from emp where deptno in(10,30) order by sal limit 0,3;

猜你喜欢

转载自blog.csdn.net/weixin_44296929/article/details/108577763
今日推荐