MySQL 条件语句列表

45 阅读2分钟

以下是 MySQL 中常用的条件语句,全部以小写形式列出并说明:

1. 基础比较条件

  • =:等于

    sql

    复制

    下载

    select * from users where age = 25;
    
  • <> 或 !=:不等于

    sql

    复制

    下载

    select * from products where price <> 100;
    
  • >:大于

    sql

    复制

    下载

    select * from orders where amount > 1000;
    
  • <:小于

    sql

    复制

    下载

    select * from students where score < 60;
    
  • >=:大于等于

    sql

    复制

    下载

    select * from employees where salary >= 5000;
    
  • <=:小于等于

    sql

    复制

    下载

    select * from inventory where quantity <= 10;
    

2. 范围条件

  • between ... and ...:在某个范围内(包含边界)

    sql

    复制

    下载

    select * from products where price between 50 and 100;
    
  • not between ... and ...:不在某个范围内

    sql

    复制

    下载

    select * from employees where salary not between 3000 and 6000;
    

3. 集合条件

  • in (...):在指定值列表中

    sql

    复制

    下载

    select * from customers where id in (1, 3, 5);
    
  • not in (...):不在指定值列表中

    sql

    复制

    下载

    select * from cities where country_code not in ('US', 'CA');
    

4. 模糊匹配条件

  • like:模式匹配

    sql

    复制

    下载

    select * from users where name like 'john%';
    
  • not like:不匹配模式

    sql

    复制

    下载

    select * from products where name not like '%test%';
    
  • regexp 或 rlike:正则表达式匹配

    sql

    复制

    下载

    select * from articles where title regexp '^[0-9]';
    
  • not regexp:不匹配正则表达式

    sql

    复制

    下载

    select * from logs where message not regexp 'error';
    

5. 空值判断条件

  • is null:是空值

    sql

    复制

    下载

    select * from orders where shipped_date is null;
    
  • is not null:不是空值

    sql

    复制

    下载

    select * from employees where manager_id is not null;
    

6. 逻辑组合条件

  • and:逻辑与

    sql

    复制

    下载

    select * from products where price > 100 and stock > 0;
    
  • or:逻辑或

    sql

    复制

    下载

    select * from users where age < 18 or age > 65;
    
  • not:逻辑非

    sql

    复制

    下载

    select * from customers where not (status = 'inactive');
    
  • xor:逻辑异或(MySQL特有)

    sql

    复制

    下载

    select * from permissions where read xor write;
    

7. 特殊条件

  • exists (...):子查询返回结果存在

    sql

    复制

    下载

    select * from departments d where exists (select 1 from employees e where e.dept_id = d.id);
    
  • not exists (...):子查询返回结果不存在

    sql

    复制

    下载

    select * from products p where not exists (select 1 from inventory i where i.product_id = p.id);
    
  • case ... when ... then ... else ... end:条件选择

    sql

    复制

    下载

    select name, case when score >= 90 then 'A' when score >= 80 then 'B' else 'C' end as grade from students;
    

8. JSON条件(MySQL 5.7+)

  • json_contains:JSON包含特定值

    sql

    复制

    下载

    select * from products where json_contains(tags, '"sale"');
    
  • json_contains_path:JSON包含特定路径

    sql

    复制

    下载

    select * from users where json_contains_path(profile, 'one', '$.address.city');