先上代码吧
SELECT `notice`.`id` , `notice`.`fid` , `notice`.`has_read` , `notice`.`notice_time` , `notice`.`read_time` , `f`.`fnum` , `f`.`forg` , `f`.`fdst` , `f`.`actual_parking` AS `parking` , `f`.`scheduled_deptime` , `f`.`estimated_deptime` , `f`.`actual_deptime` , `f`.`scheduled_arrtime` , `f`.`estimated_arrtime` , `f`.`actual_arrtime` , `f`.`is_vip` , `f`.`aoc_notice`
FROM (
select
t.id,
t.fid,
t.has_read,
t.notice_time,
t.read_time
from
(
select
a.id,
a.fid,
a.has_read,
a.notice_time,
a.read_time,
@v_rownum := @v_rownum+1,
if(@v_fid=a.fid,@v_rowid:[email protected]_rowid+1,@v_rowid:=1 ) as row_count,
@v_fid:=a.fid
from
(
SELECT
id,
fid,
has_read,
notice_time,
read_time
FROM vkm_user_notice_flight
where `notice_type` = ‘process_update‘ and uid=82
order by fid, notice_time desc
) a,
(
select @v_rownum:=0, @v_rowid:=0, @v_fid:=null
) b
) t
where t.row_count =1
) AS `notice`
LEFT JOIN `vkm_flight` AS `f` ON `notice`.`fid` = `f`.`id`
LEFT JOIN `vkm_parking` AS `parking` ON `f`.`actual_parking` = `parking`.`parking_num`
在工作中朋友发来了一段这样的sql语句 一开始我 就蒙了 根本不懂啊!因为个人的mysql也不是很精通只会简单的增删改而已其实,以上代码很直接的写法就是
SELECT `notice`.`id` , `notice`.`fid` , `notice`.`has_read` , `notice`.`notice_time` , `notice`.`read_time` , `f`.`fnum` , `f`.`forg` , `f`.`fdst` , `f`.`actual_parking` AS `parking` , `f`.`scheduled_deptime` , `f`.`estimated_deptime` , `f`.`actual_deptime` , `f`.`scheduled_arrtime` , `f`.`estimated_arrtime` , `f`.`actual_arrtime` , `f`.`is_vip` , `f`.`aoc_notice`
FROM `notice` LEFT JOIN `vkm_flight` AS `f` ON `notice`.`fid` = `f`.`id` LEFT JOIN `vkm_parking` AS `parking` ON `f`.`actual_parking` = `parking`.`parking_num`
但是以上代码的查询效率真的是差别太大了!具体的上面的那串代码我还没明白方式,也请求指导中,但是上网百度了一下 一个是mysql中if的使用还有一个就是mysql中用户变量的使用
用户名量的设置可以通过set var [email protected]:=val;
mysql中if的使用if(exp1,exp2,exp3) 在if中如果exp1为true则执行exp2否则执行exp3;
现在再看上述的代码的话可能就简单多了!根据上述的代码我又重新自己写了一个简单的应用实例
select id,fnum,forg,fdst,@v_rownum:[email protected]_rownum+1 from vkm_flight,(select @v_rownum:=0) b
原文:http://www.cnblogs.com/huixingwo/p/4615308.html