MySQL学习笔记——查询(DQL)

查询 DQL

1.基础查询

语法

select 要查询的内容 from 表名
要查询的内容包括:表中的字段、常量、表达式、函数

查询单个字段

select 字段名 from 表名;

查询多个字段

select 字段名,字段名,字段名 from 表名;
字段名中间用英文逗号隔开

查询表中的所有字段

select * from 表名;

别名

select 字段名 as 别名,字段名 as 别名 from 表名;
如果别名中有空格等特殊符号,可以给别名加上双引号`“别名”

去重

select distinct 字段名 from 表名;
去重添加distinct关键字

字段的拼接

select concat('字段名','字段名','字段名') as 别名 from 表名;
字段的合成使用`concat(‘字段名’,‘字段名’,‘字段名’)函数
字段拼接后最好起别名

2.条件查询

语法

select 要查询的内容 from 表名 where 条件

条件查询的分类

按照条件表达式查询

条件运算符:> < = != <> >= <=

按照逻辑表达式查询

作用:连接条件表达式
逻辑运算符:and or not
and : 两边条件都为 true 结果为true 反之为false
or : 一个条件为 true 结果为true 反之为false
not : 条件本身为 false 结果为true 反之为false

查询部门编号不是在90到110之间,或者工资高于15000的员工信息
写法1:
select * from employees where department_id<90 or department_id>110 or salary>1500

写法2:
select * from employees where not(department_id>=90 and department_id<=110) or salary>1500

模糊查询

  1. like:一般和通配符(% 多个字符 和 _ 单个字符)搭配使用
  2. between and
    • 在…之间
    • 包含临界值
  3. in
    • 用于判断某字段的值是否属于in列表中的某一项
    • 列表中的值类型必须统一
    • 不支持通配符
  4. is null
    • = 或者<>不能判断null值
  5. <=> 安全等于
    • 既可以判断null也可以判断普通的数值
    • 可读性较差,不建议使用
like的使用
  1. 查询员工名中包含字符a的员工信息
    select * from employees where last_name like '%a%';
  2. 查询员工中第三个字符为e,第五个字符为a的员工名和工资
    select last_name,salary from employees where last_name like '__e_a%';
  3. 查询员工名中第二个字符为_的员工名
    select last_name from employees where last_name like'_\_%';# \转义
    select last_name from employees where last_name like'_!_%' escape '!';# escape关键词定义转义字符
between and 的使用
  1. 查询员工编号在100到120之间的员工信息
    select * from employees where employee_id between 100 and 120;
in 的使用
  1. 查询员工的工种编号 IT_PROG、AD_VP、AD_PRES中的一个员工名和工种编号
    select last_name,job_id from where job_id in('IT_PROG', 'AD_VP','AD_PRES');
is null 的使用
  1. 查询没有奖金的员工名和奖金率
    select last_name,commission_pct from employees where commission_pct is null;
  2. 查询有奖金的员工名和奖金率
    select last_name,commission_pct from employees where commission_pct is not null;
<=> 安全等于
  1. 查询没有奖金的员工名和奖金率
    select last_name,commission_pct from employees where commission_pct <=> null;

3.排序查询

语法

select 查询列表 from 表 where 条件 order by 排序 asc(升)/desc(降)
例: 查询员工信息,要求工资从高到低排序
select * from employees order by salary desc;

总结

order by

  • 支持单个字段
  • 支持多个字段
  • 支持表达式、函数、别名
  • 一般放在查询语句的最后面,limit字句除外

4.分组查询

发布了15 篇原创文章 · 获赞 20 · 访问量 1917

猜你喜欢

转载自blog.csdn.net/OliverND/article/details/103439064
今日推荐