如何在mysql中将行与不完美配对?不完美,意味着行不完全匹配为in和out。有时候,有两个人一个人或者一个人没有人,或者两个人或者更多个人一个人或者根本没有人。 表格如下:
| id | action | date |
+----+--------+---------------------+
| 1 | in | 19.1.2012 15:41:52 |
| 1 | out | 19.1.2012 15:55:52 |
| 2 | in | 19.2.2012 15:55:52 |
| 2 | out | 19.2.2012 17:55:53 |
| 1 | in | 19.3.2012 15:55:54 |
| 1 | in | 19.3.2012 17:55:55 |
| 1 | out | 19.3.2012 19:55:56 |
| 3 | in | 19.4.2012 15:55:57 |
| 3 | out | 19.4.2012 17:55:58 |
| 3 | out | 19.4.2012 19:55:59 |
+----+--------+---------------------+
期望的结果是这样的:
+----+--------+---------------------+
| id | action | date |
+----+--------+---------------------+
| 1 | in | 19.1.2012 15:41:52 |
| 1 | out | 19.1.2012 15:55:52 |
| 2 | in | 19.2.2012 15:55:52 |
| 2 | out | 19.2.2012 17:55:53 |
| 1 | in | 19.3.2012 17:55:55 |
| 1 | out | 19.3.2012 19:55:56 |
| 3 | in | 19.4.2012 15:55:57 |
| 3 | out | 19.4.2012 17:55:58 |
+----+--------+---------------------+
这是最令人满意的结果
+----+---------------------+---------------------+
| id | date_in | date_out |
+----+---------------------+---------------------+
| 1 | 19.1.2012 15:41:52 | 19.1.2012 15:55:52 |
| 2 | 19.2.2012 15:55:52 | 19.2.2012 17:55:53 |
| 1 | 19.3.2012 17:55:55 | 19.3.2012 19:55:56 |
| 3 | 19.4.2012 15:55:57 | 19.4.2012 17:55:58 |
+----+---------------------+---------------------+
这是一个代码,但它产生不同的结果,任何人都可以找出错误的位置?
在这里输入代码SELECT c.e_id
,CAST(c.in_time AS DATETIME)AS in_time
,c.out_time
FROM(
SELECT IF(@prev_id = d.id,@ in_time,@ in_time:= NULL)AS reset_in_time
,@ in_time:= IF(d.action ='in',d.date,@ in_time)AS in_time
,IF(d.action ='out',d.date,NULL)AS out_time
,@ prev_id:= d.id AS id
FROM(
SELECT id,date_,action
来自e
JOIN(SELECT @prev_id:= NULL,@ in_time:= NULL)f
ORDER BY id,date,action
)d
) C
在哪里c.out_time不是NULL
订购c.out_time enter code here
答案 0 :(得分:2)
如果事件c中存在相同id的事件c,则选择a事件为a,out事件为b并使用LEFT JOIN
来消除该行;这将简单地得到所有进/出时间,它们之间没有额外的进出。
SELECT a.id, a.date date_in, b.date date_out
FROM mytable a
JOIN mytable b
ON a.id = b.id AND a.date < b.date
LEFT JOIN mytable c
ON a.id = c.id AND c.date < b.date AND c.date > a.date
WHERE a.action = 'in' AND b.action = 'out' AND c.action IS NULL
ORDER BY a.date;