Per le domande relative a mysql esiste la sezione php.

L'idea di massima dovrebbe essere questa:

codice:
select *, 
sec_to_time(unix_timestamp(stato_5) - unix_timestamp(stato_0) - if(stato_2 is not null,unix_timestamp(stato_3) - unix_timestamp(stato_2),0)) as tempo
from (
select nome,
max(case when stato = 0 then orario else null end ) as stato_0,
max(case when stato = 1 then orario else null end ) as stato_1,
max(case when stato = 2 then orario else null end ) as stato_2,
max(case when stato = 3 then orario else null end ) as stato_3,
max(case when stato = 5 then orario else null end ) as stato_5
from tabella
group by nome) as tab
Presumo che i tuoi campi siano di tipo datetime e non time come nel tuo esempio e che debba raggruppare non solo per nome.