您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

mysql实例---sql语句中使用@变量_MySQL

2026/1/31 11:16:37发布19次查看
bitscn.com本文介绍下,在mysql语句中使用@变量的一个例子,学习下这个特殊变量的用法,有需要的朋友参考下吧。要求:
计算用户距上次访问的天数,根据imei号区分不同的用户,如果时间段内只有一次访问则为0。
初始化数据:
复制代码代码示例:create table `pd` ( 
  `imei` varchar(32) not null default '', 
  `dat` datetime default null 
) engine=innodb default charset=utf8;
-- ---------------------------- 
-- records of pd 
-- www.jbxue.com
-- ---------------------------- 
insert into `pd` values ('1', '2013-07-25 00:00:01'); 
insert into `pd` values ('1', '2013-07-26 00:00:02'); 
insert into `pd` values ('2', '2013-07-23 00:00:04'); 
insert into `pd` values ('2', '2013-07-26 00:00:03'); 
insert into `pd` values ('3', '2013-07-26 00:00:01');
脚本,使用@特殊变量:
复制代码代码示例:select * from ( 
    select imei user_id, max(max_dd) , max(max_dd_2), to_days( max(max_dd)) - to_days(max(max_dd_2)) days  from (
        select imei, max_dd, max_dd_2 from ( 
              select tmp.imei, tmp.dates, 
                           if(@imei=tmp.imei, @rank:=@rank+1,@rank:=1) as rank, 
                      if(@rank = 1, @max_d := tmp.dates, @max_d := null) as max_dd, 
                      if(@rank = 2, @max_d_2 := tmp.dates, @max_d_2 := null) as max_dd_2, 
                            @imei:=tmp.imei 
              from (select imei, dates from pb order by imei asc ,dates desc ) tmp , 
                (select @rownum :=0 , @imei := null ,@rank:=0, @max_d :=null, @max_d_2 := null) a 
      ) result 
    ) t 
    group by imei 
    having count(*) > 1 
) x where x.days >= 1 and exists (select 'x' from pb where dates > '2013-07-26 00:00:00')注意:
表数据量较大时,使用union all等操作将会有悲剧性的结果。
本文原始链接:http://www.jbxue.com/db/11874.html
bitscn.com
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product