如何在mysql中

问题描述:

配对的状态行(有人进入,然后退出),我有一个表user_status,在这里我插排:状态(进入/退出网站),什么时候。表看起来是这样的:如何在mysql中

id user_id status status_date 
94 5  Entered 2015-03-30 10:43:44 
95 5  Exited 2015-03-30 10:47:38 
96 5  Entered 2015-03-30 10:49:12 
97 3  Entered 2015-03-30 10:51:14 
98 3  Exited 2015-03-30 11:04:12 
99 5  Exited 2015-03-30 11:16:50 
100 3  Entered 2015-03-30 11:20:48 
101 5  Entered 2015-03-30 11:21:37 
102 2  Exited 2015-03-30 11:24:47 
103 2  Entered 2015-03-30 11:25:01 

现在我想创建,针对特定用户对行匹配他/她已退出状态进入和返回临时表的过程。结果应该是这样的:

id user_id status_date_start status_date_end 
1 5   2015-03-30 10:43:44 2015-03-30 10:47:38 
2 5   2015-03-30 10:49:12 2015-03-30 11:16:50 
3 3   2015-03-30 10:51:14 2015-03-30 11:04:12 
... 

我试过双内部联接,游标上user_status但我没有管理。请帮忙

+0

我做的,就像你现在正在做的一个项目,我将它们存储为充分和原材料表。对于原始表,我存储A_I,user_id,status_date。我的网站代码将确定它正在进入或退出。如果它正在进入,我将把'INSERT INTO完整的VALUES('',user_id,last_id,'')'last_id是A_I从原始表中返回。如果它正在退出,我将'更新完整的SET status_date_end = last_id WHERE id = this_id'。 – AkiEru

刚刚玩了一下这一点,并得到它在查询中额外的选择。

-- set up some test data 
GO 
DECLARE @moves TABLE 
    (
     id INT, 
     user_id INT, 
     status NVARCHAR(MAX), 
     status_date DATETIME 
    ) 

INSERT INTO @moves VALUES (94, 5 , 'Entered', '2015-03-30 10:43:44') 
INSERT INTO @moves VALUES (95, 5 , 'Exited', ' 2015-03-30 10:47:38') 
INSERT INTO @moves VALUES (96, 5 , 'Entered', '2015-03-30 10:49:12') 
INSERT INTO @moves VALUES (97, 3 , 'Entered', '2015-03-30 10:51:14') 
INSERT INTO @moves VALUES (98, 3 , 'Exited', '2015-03-30 11:04:12') 
INSERT INTO @moves VALUES (99, 5 , 'Exited', '2015-03-30 11:16:50') 

-- original data -- 
SELECT * FROM @moves 


-- selecting the exit date into the original data -- 
SELECT 
    m.id 
    ,m.user_id 
    ,m.status_date 
    ,(
     SELECT TOP 1 status_date 
     FROM @moves x 
     WHERE x.user_id = m.user_id 
     AND x.status = 'Exited' 
     AND x.id > m.id 
    ) as 'exit' 
FROM @moves m 
WHERE m.status ='Entered' 

结果:

enter image description here

+0

我使用mysql,所以唯一的改变是将TOP 1更改为LIMIT 1并且它可以正常工作!谢谢@JensB,你太棒了 – zofia