对sql的一些特殊操作

97 阅读3分钟

微信技术群:Day9884125

一 查询null值

1.1 背景

   你想查找特定列的值为null的所有行。

1.2 方案

   要判断一个值是否是null,必须使用is null。因为null不会等于或者不等于任何值,甚至不能和自身做比较。因此不能使用=或!=来测试某一列的值是否为null。判断一行是否含有null,必须使用is null。你也可以使用is not null来找到给定列的值是不是null

select * from user where email is null

二 把null值转化为实际值

2.1 背景

   有一些行包含null值,但是你想在返回结果里将其替换为非null的值。

2.2 方案

   你可以使用coalesce函数将null值替换为实际值。
   当然你也可以使用case...when实现

// coalesce演示,如果email中的值为null时,将结果显示为0
select coalesce(email, 0) from user 

// case...when演示,
select case when email is not null then 2
       else 0
       end
from user

三 对字段进行排序

3.1 对多字段进行排序

   注意:desc表示降序排序,order by默认是升序

select id, name, age, sex, address
from user
order by id, age desc

3.2 根据子串进行排序

// 根据这个字段的最后两个字进行排序
select id, name, age, sex, address
from user
order by substr(name, length(name)-2)

3.3 排序时对null值的处理

   如果你想按照user表的email列结果进行排序,但该字段可能是null。因此,你需要想个办法指定是否应该将null值排到最后面或者最前面。

//null值age升序排列,null值的放在最后面
select id, name, age, address 
from (
    select id, name, age, address,
        (case when age is null then 0 else 1 end) as is_null
    from user
) m
order by is_null desc, age

// 优化 待验证sql是否可以正确执行
select id, name, age, address 
from user
order by case when age is null then -1 else age end

四 插入、更新和删除

4.1 插入

   插入可以解决一行数据这样的简单问题。然而,在大多数情况下,都是基于集合的方法来创建新行,效率更高。

// 插入一行数据
insert into user (id, name, age, address) values(1, 'zhangsan', 12, '河北')

// 插入多行数据,或者将一个表中某些数据插入到另一个表中
insert into user (id, name, age, address)
select id, name, age, address
from user_info
where age>18

4.2 复制表定义

   你想创建一个新表,该表与当前已存在的表保持相同的结构定义。例如,你希望分库分表创建一个新的表存放新产生的数据。你只想复制表结构而不是复制数据。

create table user_202302 like user_202301

五 获取mysql元数据

   元数据:即表名的定义数据,包括列定义、索引定义。可通过语句查询

// 其中user是你要查询的表名
show create table user