0

Estou querendo listar o último registro da tabela e exibir, mas não estou conseguindo.

A tabela reports tem o campo registration date duration e destination_id

registration   date       time         duration         destination_id
    2501    2014-03-22  08:25:00  00:40:00(timestamp)      SBGL
    2501    2015-07-25  10:03:00  00:40:00(timestamp)      SBRJ
    5531    2015-09-15  19:24:00  00:40:00(timestamp)      SBSM
    5531    2015-10-19  10:15:00  00:40:00(timestamp)      SBBR

Quero mostrar o ultimo destination_id para o registration 2501 e 5531. Ou seja mostrar que:

2501 => SBRJ
5531 => SBBR

No cógido abaixo ele retorna:

2501 => SBGL
5531 => SBSM

Alguém ajuda pf?

$hours = mysql_query("SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( duration ) ) ) AS duration_sum FROM reports GROUP BY registration");
$regist = mysql_query("SELECT registration AS regist FROM reports GROUP BY registration");
$model = mysql_query("SELECT equipment AS model FROM reports GROUP BY registration");
$base = mysql_query("SELECT destination_id FROM reports");

while($row = mysql_fetch_array($hours) AND $row2 = mysql_fetch_array($regist) AND $row3 = mysql_fetch_array($model) AND $row4 = mysql_fetch_array($base)){

<tr>
  <td align="center"><div align="left"><? echo($row3['model']); ?></div></td>
  <td align="center"><div align="left"><? echo($row2['regist']); ?></div></td>
  <td align="center"><div align="center"><? echo($row['duration_sum']); ?></div></td>
   <td align="center"><div align="center"><? echo($row4['destination_id']); ?></div></td>
</tr>
  <?php
        }//while

1 Resposta 1

1

Precisas alterar a tua query para obter o destination_id correspondente à data mais recente. Isto pode ser feito da seguinte forma:

select registration, destination_id
from reports r
inner join 
( 
    select registration, max(timestamp(`date`, `time`)) maxT
    from reports
    group by registration
) MaxTime
  on MaxTime.registration = r.registration 
 and MaxTime.MaxT = timestamp(`date`, `time`)
order by 1

Para a seguinte estrutura

registration   date       time         duration                 destination_id
2501           2014-03-22  08:25:00    00:40:00(timestamp)      SBGL
2501           2015-07-25  10:03:00    00:40:00(timestamp)      SBRJ
5531           2015-09-15  19:24:00    00:40:00(timestamp)      SBSM
5531           2015-10-19  10:15:00    00:40:00(timestamp)      SBBR

A query irá produzir o seguinte resultado:

registration   destination_id
2501           SBRJ
5531           SBBR

Podes ver o SQLFiddle

3
  • O resultado está perfeito, mas como eu escrevo a linha: 10/11/2015 às 13:34
  • while ($row = mysql_fetch_assoc($result) ){ 10/11/2015 às 13:34
  • 1
    consegui obrigado!!! 10/11/2015 às 14:04

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .