Mysql 列变行其中一种做法。
需求是:
上班打卡记录 和 下班打卡记录 是分别是两条数据,现在是要合并为一条数据,并且封装成一个实体。
有可能是 只有上班记录,,或者是只有下班的记录。如何关联全查,一边为null或者另一边为null都需要显示出来。
SELECT * FROM
(
SELECT t1.*,t2.* FROM
(
SELECT a.id AS aid,a.location AS alocation ,DATE_FORMAT(a.time,'%Y-%m-%d') AS timePM FROM biz_attendance a WHERE a.`status`=1 AND DATE_FORMAT(a.time,'%Y-%m')=DATE_FORMAT('2018-04-11','%Y-%m')
) t1
LEFT JOIN
(
SELECT b.id AS bid,b.location AS blocation,DATE_FORMAT(b.time,'%Y-%m-%d') AS timeAM FROM biz_attendance b WHERE b.`status`=2 AND DATE_FORMAT(b.time,'%Y-%m')=DATE_FORMAT('2018-04-11','%Y-%m')
) t2
ON t1.timePM = t2.timeAM
) flag1
UNION
SELECT * FROM
(
SELECT t1.*,t2.* FROM
(
SELECT a.id AS aid,a.location AS alocation ,DATE_FORMAT(a.time,'%Y-%m-%d') AS timePM FROM biz_attendance a WHERE a.`status`=1 AND DATE_FORMAT(a.time,'%Y-%m')=DATE_FORMAT('2018-04-11','%Y-%m')
) t1
RIGHT JOIN
(
SELECT b.id AS bid,b.location AS blocation,DATE_FORMAT(b.time,'%Y-%m-%d') AS timeAM FROM biz_attendance b WHERE b.`status`=2 AND DATE_FORMAT(b.time,'%Y-%m')=DATE_FORMAT('2018-04-11','%Y-%m')
) t2
ON t1.timePM = t2.timeAM
) flag2