Frage

I'm having a small problem working out how to write this code. I have a MySQL query that returns a list of shift dates. Data returned looks like this:

id |    date    |  stime   |  etime   | staff | client
------------------------------------------------------
1  | 2014-01-01 | 08:00:00 | 08:30:00 | Dave  | Mary
2  | 2014-01-01 | 08:35:00 | 09:05:00 | Dave  | Clive
3  | 2014-01-01 | 09:17:00 | 09:32:00 | Dave  | Joan
4  | 2014-01-01 | 09:38:00 | 10:08:00 | Dave  | Doris

I need to work out the gap between calls. I.e. the gap between etime in row 1 AND stime in row 2. The answer should be 5. I can work out the difference easily using PHP, but cannot work out how to get the: etime from row 1, the stime from row 2, then the etime from row 2 and the stime from row 3 etc...... and so on... I guess some kind of alternating function, but don't know.

I do need to point out that the id will not will not be contiguous.

I am a newbie to this site and have looked around to see if this question has already been asked. I apologise if it has. Thanks to anyone who can help.

EDIT: @sean has answered the question for me except that the id results had to be continuous. I need to find out how to do a LEFT JOIN with non-continuous id

War es hilfreich?

Lösung 2

Ok! I have worked it out, with help from @Sean and my Auntie Lou :D. I am sure there is an easier way to do it though.

I have decided to create a new table and copy the information needed into it and generate new id's. As I am only working on a small database I am not worried about overheads.

Firstly CREATE a new table (temp_gaps), then SELECT the required information from the original table (placements) excluding the id column. This copies the data from the original table to the new one without ID's. The new table generates a new auto_increment ID so everything is now in order in the new table:

CREATE TABLE temp_gaps 
(
  `id` mediumint(6) NOT NULL auto_increment,
  `date` date NOT NULL,
  `stime` time NOT NULL,
  `etime` time NOT NULL,
  `staff` varchar(50) NOT NULL,
  `client` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
)
engine=memory AS 
  (SELECT date,stime,etime,staff,client 
   FROM   placements 
   ORDER  BY `staff`,`date`,`stime` ASC)

Once the information is copied I can then use @Sean previous answer to pull the information, left_join the etime column and I can then work on the data result in my PHP script. Once i'm done I just drop the table and all is good.

Thanks to Sean for sending me in exactly the right direction.

Andere Tipps

Use a LEFT JOIN to join the next row stime. Make sure to rename the t2.stime so it is not ambiguous.

SELECT t1.*, 
       t2.stime as `nxt_row_stime` 
FROM table t1 
LEFT JOIN table t2 
ON t2.id = t1.id+1

note: this requires that there is no gaps in the id increment.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top