如何通过以下条件检索数据?

时间:2013-08-14 05:58:31

标签: mysql sql select

+--------+------+---------------------+
| userId | Cmd  | Time                |
+--------+------+---------------------+
|      1 |  A   | 2013-06-21 13:15:08 |
|      1 |  B   | 2013-07-31 15:58:53 |
|      3 |  A   | 2013-07-31 16:01:42 |
|      4 |  A   | 2013-05-01 11:05:08 |
|      4 |  B   | 2013-07-31 16:06:32 |
|      6 |  B   | 2013-07-31 17:16:08 |
|      7 |  A   | 2013-04-06 17:20:36 |
|      3 |  B   | 2013-04-15 06:26:14 |
|      7 |  B   | 2013-07-31 14:53:49 |
|      6 |  A   | 2013-07-31 09:56:27 |
+--------+------+---------------------+

如何获取最后一个Cmd为B的用户ID?

预期结果:

+--------+------+---------------------+
| userId | Cmd  | Time                |
+--------+------+---------------------+
|      1 |  B   | 2013-07-31 15:58:53 |
|      4 |  B   | 2013-07-31 16:06:32 |
|      6 |  B   | 2013-07-31 17:16:08 |
|      7 |  B   | 2013-07-31 14:53:49 |
+--------+------+---------------------+

4 个答案:

答案 0 :(得分:2)

在这里,您需要使用MAX(Time)UserIdCmd='B'进行自我加入,如下所示:

SELECT t1.* FROM Table1 t1
JOIN
(
   SELECT UserId, MAX(Time) MaxTime FROM Table1
   GROUP BY UserID
)t2
ON t1.UserID = t2.UserId
AND t1.Time = t2.MaxTime
AND t1.Cmd = 'B';

输出:

| USERID | CMD |                        TIME |
----------------------------------------------
|      1 |   B | July, 31 2013 15:58:53+0000 |
|      4 |   B | July, 31 2013 16:06:32+0000 |
|      6 |   B | July, 31 2013 17:16:08+0000 |
|      7 |   B | July, 31 2013 14:53:49+0000 |

请参阅this SQLFiddle

答案 1 :(得分:1)

首先获取每个Cmd的最后日期,然后选择与该日期匹配的记录:

SELECT userId
FROM SomeTable
JOIN ( SELECT Cmd,
              MAX(Time) AS MaxTime
       FROM SomeTable
       GROUP BY Cmd
     ) MaxTable ON SomeTable.Cmd = MaxTable.Cmd
               AND SomeTable.Time = MaxTable.MaxTime

如果您只想要B记录:

SELECT userId
FROM SomeTable
JOIN ( SELECT Cmd,
              MAX(Time) AS MaxTime
       FROM SomeTable
       GROUP BY Cmd
       WHERE Cmd = 'B'
     ) MaxTable ON SomeTable.Cmd = MaxTable.Cmd
               AND SomeTable.Time = MaxTable.MaxTime

修改 误解了这个问题。见hims056的答案。他做的和我一样,但是在UserId而不是Cmd上进行分组。比较:

SELECT SomeTable.*
FROM SomeTable
JOIN ( SELECT userId,
              MAX(Time) AS MaxTime
       FROM SomeTable
       GROUP BY userId

     ) MaxTable ON SomeTable.userId= MaxTable.userId
               AND SomeTable.Time = MaxTable.MaxTime
WHERE SomeTable.Cmd = 'B'

答案 2 :(得分:0)

查询是:

SELECT userID
FROM TABLE_COMMANDE
WHERE 
(
 TIME = (SELECT MAX(TIME) FROM TABLE_COMMANDE WHERE CMD LIKE 'B')
)

答案 3 :(得分:-1)

select userID
from your_table
where CMD like 'B'