MySQL笔记

MySQL里的日期与时间

格式化:select DATE_FORMAT(now(), ‘%Y-%m-%d %T’);
从1970年1月1日到指定时间的天数:select to_days(now());

取当前时间:
select now(), current_timestamp(),current_timestamp,current_time, curtime(),current_date, curdate(), sysdate();
sysdate()函数是这个函数执行时候的时间,其它的是语句开始执行的时间。

时间的加减:

DATE_ADD(date,INTERVAL expr type)
DATE_SUB(date,INTERVAL expr type)
DATEDIFF(date1,date2),2个时间的天数
TIMESTAMPDIFF(type,date1,date2),2个时间的差额
TIMESTAMPADD(type,int_expr,date1),加时间

 

存储过程

set @var = '';
set @var2 = 'fff';
set @var = @var2;

-- 这种只能用在declare了的变量
set var = 'sdfdf';

-- 这里不会输出返回结果,只会设置变量
select `day` into @var from redash_queue_flush_sem_base_data limit 1;
-- 这里在设置变量的同时,也会返回
select @day:=`day` from redash_queue_flush_sem_base_data limit 1;


CREATE DEFINER=`dealam_stat_prod`@`%` PROCEDURE `flush_sem_base_data`()
-- 注意这里的BYEBYE,在里面用leave BYEBYE就可以退出了,存储过程里没有return之类的功能
BYEBYE:BEGIN
    declare vday varchar(100);
    declare vvar VARCHAR(50);
    declare vvalue VARCHAR(200);
    declare select_done int default 0;
    -- 定义select游标
    declare cur_queue cursor for select `var`, `value` from redash_variable limit 2;
    -- 定义游标是否循环完成的标记变量
    declare continue handler for not found set select_done = 1;
    
    if @queue_count > 0 then
        insert into redash_logs (`what`) values (concat('刷新队列里还有数据:', @queue_count));
        select concat('刷新队列里还有数据:', @queue_count) as msg;
        leave BYEBYE;
    else
        -- 找出待更新订单对应的订单日期,放入待刷新队列中
        insert ignore redash_queue_flush_sem_base_data 
            select distinct(from_unixtime(transaction_time, '%Y-%m-%d')) from da_sem_order where updated_time>@sem_last_update_time order by updated_time;
    end if;
    
    open cur_queue;
    
    loop_label:loop
        -- 注意这里变量前没有加@
        fetch cur_queue into vvar, vvalue;
        -- select_done 前没有加@
        if select_done = 1 then
            leave loop_label;
        end if;
        
        -- 注意这里变量前也没有加@,也就是说如果是declare的变量,好像是不用加的
        select vvar, vvalue;
        set @vvar2 = vvar;
        select @vvar2;
        insert into redash_logs (`what`) values (concat('刷新了sem base data,日期:', vvar));
        
    end loop;
    
END

 

查看未提交的事务
select trx_state, trx_started, trx_mysql_thread_id, trx_query from information_schema.innodb_trx\G;

查看锁信息
select * from information_schema.INNODB_TRX WHERE trx_state=’LOCK WAIT’\G