博客
关于我
mysql条件查询
阅读量:788 次
发布时间:2023-02-12

本文共 1838 字,大约阅读时间需要 6 分钟。

一 条件查询的格式

在使用 SQL 进行数据查询时,基本的查询格式通常包括以下几个部分:

  • select 查询列表

    使用 select 语句指定需要查询的字段。例如:

    select last_name, salary from employees
  • from 表名

    指定要查询的数据库表。例如:

    select last_name, salary from employees
  • where 查询条件

    使用 where 子句指定查询的条件。常用的条件运算符包括 >, <, =, !=, >=, <=, <>, => 等。

    • => 是安全等于,既可以用于判断数值类型,也可以用于判断是否为 null
      例如:
    select salary from employees where salary > 10000

  • 二 查询条件的分类

    在 SQL 中,查询条件可以根据不同的需求进行分类。以下是常见的分类方法:

    1. 按简单条件表达式筛选

    简单的条件运算符可以直接用于比较两个字段或值。

    • 常见的条件比较符包括 >, <, =, !=, >=, <=, <>, => 等。
      例如:
      select last_name, salary from employees where salary > 10000

    2. 按逻辑表达式筛选

    当需要结合多个条件时,可以使用逻辑运算符 ANDOR

    • AND 表示所有条件都必须满足。
    • OR 表示只要有一个条件满足即可。
      例如:
      select last_name, salary from employees where salary > 10000 and salary < 20000

    3. 模糊查询

    在某些情况下,可能需要对字段进行模糊匹配。常用的模糊查询符包括 likebetweenin 等。

    (1)like 和 通配符
    • % 可以匹配任意数量的字符,包括零个字符。
      例如:
      select last_name from employees where last_name like '%a%';
    • _ 可以匹配任意一个字符。
      例如:
      select last_name from employees where last_name like '__n_l%';
    • 如果需要匹配特定的字符,可以使用转义字符 \_
      例如:
      select last_name from employees where last_name like '_\_%';
    • 如果需要自定义转义字符,可以使用 ESCAPE 关键字。
      例如:
      select last_name from employees where last_name like '_$_%' escape '$';
    (2)between and
    • between and 用于判断一个字段的值是否在两个特定值之间,包括端点值。
      例如:
      select employee_id from employees where employee_id between 100 and 120;
    • 如果需要排除某个端点值,可以使用 not between
      例如:
      select last_name, salary from employees where salary not between 8000 and 17000 order by salary DESC;
    (3)in
    • in 用于判断一个字段的值是否属于指定列表中的某一项。列表中的值必须与字段类型一致,且不支持通配符。
      例如:
      select last_name, job_id from employees where job_id in ('IT_PROG', 'AD_VP', 'AD_PRES');
    (4)is nullis not null
    • is null 用于判断一个字段是否为 null
      例如:
      select employee_id, last_name from employees where commission_pct is null;
    • is not null 用于判断一个字段不为 null
      例如:
      select employee_id, last_name from employees where commission_pct is not null;

    通过以上方法,可以根据需求灵活构建查询条件,从而高效地筛选出符合要求的数据。

    转载地址:http://widfk.baihongyu.com/

    你可能感兴趣的文章
    MySQL的函数
    查看>>
    mysql的函数DATE_ADD()
    查看>>
    mysql的函数操作
    查看>>
    mysql的分类排名_mysql高低排名
    查看>>