mysql组结果为单表行

时间:2017-02-05 08:36:36

标签: php mysql arrays

我有这个查询,它返回度假村(res_id)接下来三天的最高温度(temp在t0,t1,t2)。我希望每个度假村有一排预测(多个度假村)。我怎么能这样做?

查询结果

res_id  lud             temphi
1       2017-02-05      -5
1       2017-02-06      -2   
1       2017-02-07      -8
4       2017-02-05      2
4       2017-02-06      1
4       2017-02-07      -1

期望的结果

res_id      t0      t1      t2
1           -5      -2      -8
4           2       1       -1




$rQuery1 = "SELECT a.lud, a.temphi,a.res_id
FROM sv_snowalert a
LEFT JOIN sv_orte b ON a.res_id = b.res_id AND b.ski_id>0
INNER JOIN sv_canton c ON b.can_id = c.can_id
INNER JOIN sv_country d ON c.cou_id = d.cou_id
WHERE a.lud>='2017-02-05' GROUP BY a.res_id, a.lud ORDER BY a.res_id, a.lud ASC";
$rResult1 = mysql_query($rQuery1);

$seq=0;
$num_rows = mysql_num_rows($rResult1)
while ($rows1 = mysql_fetch_array($rResult1))
{
$seq++;
 // output

}

1 个答案:

答案 0 :(得分:1)

这里只是一个mysql提示:

select
    a.res_id,
    max(case when date(a.lud) = date_add(curdate(), interval 0 day) then temphi else null end) as t0,
    max(case when date(a.lud) = date_add(curdate(), interval 1 day) then temphi else null end) as t1,
    max(case when date(a.lud) = date_add(curdate(), interval 2 day) then temphi else null end) as t2
from sv_snowalert a
left join sv_orte b on a.res_id = b.res_id and b.ski_id > 0
inner join sv_canton c on b.can_id = c.can_id
inner join sv_country d on c.cou_id = d.cou_id
where a.lud between curdate() and date_add(curdate(), interval 2 day)
group by a.res_id
order by a.res_id asc

demo在这里。