mysql中查询语句;时间差;空;

1.查询时间区间;

 

select time_to_sec(timediff('2022-02-18 10:06:00', '2022-01-25 10:49:00')); #时间太大,算的有问题;
select timestampdiff(second, '2022-01-25 10:49:00','2022-02-18 10:06:00');
select unix_timestamp('2022-02-18 10:06:00')-unix_timestamp( '2022-01-25 10:49:00');

2.查询表结构;

show create table 表名;

3.case when函数;

第一种格式:简单 Case函数;

格式说明    

    case 列名

    when   条件值1   then  选项1

    when   条件值2    then  选项2.......

    else     默认值      end

eg:

    select 
    case   job_level
    when     '1'     then    '1111'
    when   '2'     then    '1111'
    when   '3'     then    '1111'
    else       'eee' end
    from     dbo.employee

第二种格式:Case搜索函数

格式说明    

    case  

    when  列名= 条件值1   then  选项1

    when  列名=条件值2    then  选项2.......

    else    默认值 end

eg:

    update  employee
    set         e_wage =
    case
    when   job_level = '1'    then e_wage*1.97
    when   job_level = '2'   then e_wage*1.07
    when   job_level = '3'   then e_wage*1.06
    else     e_wage*1.05
    end

参考:https://www.cnblogs.com/T8888/p/14283403.html

如,我写的

select
case when timestampdiff(second,original_create_time,cc.create_time)>=0 and timestampdiff(second,original_create_time,b.create_time)<=7200 then '0-2小时'
when timestampdiff(second,original_create_time,cc.create_time)>7200 and timestampdiff(second,original_create_time,b.create_time)<=43200 then '2-12小时'
when timestampdiff(second,original_create_time,cc.create_time)>43200 then '12小时以上'
from (select * from (select id, original_create_time,phone_mask from t_lead where provider_id=132 and original_create_time>="2021-1-1 00:00:00" and original_create_time<"2021-12-1 00:00:00" and deleted=false and disable=false and inquiry_count>0 and belong_type = 0)tl JOIN (select lead_id,create_time from (select * from t_staff_lead order by create_time asc)as a group by lead_id)b on tl.id=b.lead_id)cc ;

 4.查询列表某字段为空;

是is null 或 is NULL;不是=null;

SELECT * FROM t_lead_receive where user_id is null; #可以查询到空的行;
SELECT * FROM t_lead_receive where user_id = null;  #查询结果为空;

5.sum(case when certification_status=1 then 1 else 0 end),如果certification_status=1,则统计为1,否则统计为0;

select sum(case when trans_order_audit="true" then 1 else 0 end) from t_provider;
select count(1) from t_provider where trans_order_audit="true";
如上这2行代码是一样的;

6.distinct 去重;count(distinct origin_target_id);

count(1) 与count(字段名);

 

  

 

posted on 2022-04-20 18:16  星空6  阅读(140)  评论(0)    收藏  举报

导航