update

1条 sql 更新多张表

  1. update table1 as t1, table2 as t2 set t1.status=2, t2.name='xx'
  2. where t1.id = xx and t2.id = xx

select

条件查询

case … when .. then … end

  1. case veriable_name when veriable_value1 then do_something when veriable_value2 then do_xxxx
  2. else 剩余的情况全部走这里 end

sql 三元表达式

IF(expr1,expr2,expr3)
规则:如果 expr1 是TRUE,则返回expr2, 否则返回expr3。
这就是 sql 的三元表达式.

举例

select *,IF(sex='1','男','非男') as sex_text from user

分页查询

SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15

Mysql 查询时大小写不敏感

  1. 测试验证 Mysql 查询时对大小写不敏感
// 表结构
desc my_user;
id    int(16)
name    varchar(16)
create_time    timestamp
update_time    timestamp
// 插入数据
insert into my_user set name="AA";
// 查询
select * from my_user where binary name="Aa";
select * from my_user where binary name="aa";

这两条命令都能查询到值.

Mysql 查询时区分大小写

  1. 查询时加 binary
    select * from my_user where binary name="Aa";
    
    2, 修改表结构 / 建表的时候注意, 写上 1 个 binary
    create table some_table(
    str char(20) binary 
    )
    
    对于CHAR、VARCHAR和TEXT类型,BINARY属性可以为列分配该列字符集的校对规则。BINARY属性是指定列字符集的二元 校对规则的简写。排序和比较基于数值字符值。因此也就自然区分了大小写。

    查询不同的数据

    存在一个表中而不在另外一个表中的数据:

场景:两个不同的查询 SQL,查询结果不一致,为了比较查询结果,使用此 SQL 先建立视图;

select distinct a.order_sn from a_151 as a 
where a.order_sn not in (select order_sn from b_141);

高级查询

临时表

使用场景

数据库数量大,但是想要获取这个数据集合的一个子集。

创建临时表

create temporary table failed_statistics  
select pengine_class,count(*) as times from failed_task_step_statistics group by pengine_class;

删除临时表

drop temporary table failed_statistics;