查询将max(col)和相关col的行链接到不同的表

时间:2015-09-11 13:06:45

标签: mysql sql max inner-join

我有两张桌子:

**Inbox**
- InboxID
- PostID
- UserID
- datePosted

**Users**
- UserID
- FName
- SName
- Pic

我需要做的是在收件箱表中获取最高的datePosted val,其中userID不等于传入的特定val,并且postID IS等于我传入的val。然后我需要获取FName ,UserID的SName和Pic,与最高datePosted val。

位于同一行

我的尝试:

SELECT
    MAX(Inbox.datePosted),
    uSERS.uSERid,
    Users.FName as commenterFname, 
    Users.SName as commenterSName,
    Users.Pic as commenterPic
FROM
    Inbox
    INNER JOIN Users
        ON Inbox.UserID = Users.UserID
        WHERE PostID = 807 AND Inbox.userID <> 36

1 个答案:

答案 0 :(得分:1)

未经测试...选择datePosted等于max datePosted。

的行
   SELECT
        Inbox.datePosted as datePosted,
        uSERS.uSERid     as uSERid,
        Users.FName      as commenterFname, 
        Users.SName      as commenterSName,
        Users.Pic        as commenterPic
    FROM Inbox
      INNER JOIN Users ON Inbox.UserID = Users.UserID
    WHERE PostID = 807 AND Inbox.userID <> 36
      and datePosted = (select max(datePosted)
                        FROM Inbox
                          INNER JOIN Users ON Inbox.UserID = Users.UserID
                        WHERE PostID = 807 AND Inbox.userID <> 36)