上次用户操作的SQL查询

时间:2015-03-18 20:31:09

标签: sql sql-server

我正在尝试使用SQL语句来显示数据库中的用户列表及其上一个操作。

当前的表格格式为;

tblUser:
id,用户名,密码

tblAction:
id,uid,action,date

我目前的SQL语句是;

SELECT *
 FROM tblUser
 FULL OUTER JOIN Location
 ON tblUser.id=tblAction.uid
 WHERE action IS NOT NULL
 ORDER BY date DESC

我使用了limit 1,但这没效果。

我也试过了;

SELECT *     
FROM tblAction T1    
WHERE date = (
   SELECT max(date)
   FROM tblUser T2
   WHERE T2.uid=T1.id

请有人帮帮我吗? 这是一个在PHP管理面板中执行的SQL命令,不是MySQL。

2 个答案:

答案 0 :(得分:1)

尝试使用RANK()/DENSE_RANK()/ROW_NUMBER()

FIDDLE DEMO

<强> RANK:

;WITH CTE AS
(
    SELECT  a.*,
           b.action,
            b.date,
            Rk = RANK() OVER(PARTITION BY a.id ORDER BY b.[date] DESC)
    FROM tblUser a
    LEFT JOIN tblAction b
        ON a.id = b.uid
)
SELECT *
FROM CTE 
WHERE Rk = 1;

答案 1 :(得分:1)

使用ROW_NUMBER

;WITH CTE AS
(
    SELECT  U.*,
            A.[action],
            A.[date],
            RN = ROW_NUMBER() OVER(PARTITION BY U.id ORDER BY A.[date] DESC)
    FROM tblUser U
    LEFT JOIN tblAction A
        ON U.id = A.uid
)
SELECT *
FROM CTE 
WHERE RN = 1;