使用具有相同id part2的select将选定列值转换为另一行

时间:2013-12-18 08:43:31

标签: php mysql select row

我正在制作一个简单的时间和超时系统..我有3对进出。 P_ID(为person_id)

表A

p_id  time_id      status            timestamp
1         1           in        2013-12-18 15:44:09
2         2           in        2013-12-18 16:23:19
1         3           out       2013-12-18 18:31:11
1         4           in        2013-12-18 18:50:11
3         5           out       2013-12-18 19:20:16
1         6           out       2013-12-18 19:50:11
2         7           out       2013-12-18 19:51:19
1         8           in        2013-12-19 07:51:19
1         9           out       2013-12-19 12:00:19
1         10          in        2013-12-19 01:00:19
1         11          out       2013-12-19 05:30:19
1         12          in        2013-12-19 07:51:19
1         13          out       2013-12-19 11:00:19

进入表结果同一日期的一行

id status     timestamp        status     timestamp       status     timestamp          status      timestamp          status     timestamp       status      timestamp
1    in   2013-12-18 15:44:09   out   2013-12-18 18:31:11  in    2013-12-18 18:50:11    out     2013-12-18 19:50:11
2    in   2013-12-18 16:23:19   out   2013-12-18 19:51:19  
3                               out   2013-12-18 19:20:16
1    in   2013-12-19 07:51:19   out   2013-12-19 12:00:19  in    2013-12-19 01:00:19    out     2013-12-19 05:30:19     in    2013-12-19 07:51:19   out       2013-12-19 11:00:19

2 个答案:

答案 0 :(得分:0)

我猜你想要这样的东西:

SELECT a1.id, a.1status, a1.timestamp, a2.status, a2.timetstamp
FROM timetable a1
LEFT JOIN timetable a2 ON a2.id=a1.id AND a2.status = 'out'
WHERE a1.status = 'in'

让一行只有一个out-value对我没有任何意义。

答案 1 :(得分:-1)

尝试此查询,

select t1.id,t2.status as IN_Status,t2.timestamp as IN_Time,t3.status as OUT_Stats,t3.timestamp as OUT_Time
  from table1 t1 
   left join table1 t2 on (t1.id=t2.id and t2.status ='in')
   left join table1 t3 on (t1.id=t3.id and t3.status ='out') 
   group by t1.id;

检查示例

SQL Fiddle Example