Search code examples
mysqlyiisqlyog

How to get next row value from Mysql Query


I want to get (select) the next row value from MySql query using SQLYog, with the same id_voyage_order?

Example :

id_timesheet | id_voyage_order | Duration
----------------------------------------

1            | 106             | 0.00
2            | 106             | 24.00
3            | 210             | 12.00
4            | 106             | 12.00
5            | 210             | 24.00

i want to select it and make in View file Yii based on the same id_voyage order become like this and set the Duration of the last record become 0 :

id_timesheet | id_voyage_order | Duration
1.           | 106             | 24.00
2.           | 106             | 12.00
4.           | 106             | 0.00

Solution

  • For instance:

    SELECT a.id_timesheet
         , a.id_voyage_order
         , COALESCE(b.duration,0) duration
      FROM my_table a
      LEFT
      JOIN  
         ( SELECT x.*
                 , MAX(y.id_timesheet) previous
              FROM my_table x 
              JOIN my_table y 
                ON y.id_voyage_order = x.id_voyage_order 
               AND y.id_timesheet < x.id_timesheet 
             GROUP 
                BY x.id_timesheet
          ) b
         ON b.previous = a.id_timesheet
      WHERE a.id_voyage_order = 106;