SELECT x.*, TIMEDIFF(x.logout_date, x.login_date) as duration
FROM
(
SELECT a.user_id, a.`date` as logout_date,
(SELECT MAX(b.`date`) FROM table1 b WHERE b.`date` <a.`date`
and b.user=a.user and b.type = 'login') as login_date
FROM table1 a WHERE a.type ='logout'
)x