从其他表中选择MAX值(如果有)

时间:2014-10-07 11:48:16

标签: sql sql-server sql-server-ce

我想要实现的是非常基本的,我找到了类似的解决方案here,但我无法使用我正在使用的MS SQL Compact。

假设我有这些表:

User                    Comments
ID   | Name             UserID | Comment           | Posted
-----+-------------     -------+-------------------+----------
0    | Adam             1      | Whatever 1        | 2014-01-01
1    | Beth             1      | whatever 2        | 2014-01-02
2    | Chris            0      | Whatever 3        | 2014-01-02
3    | David            3      | Whatever 4        | 2014-01-04

我想要的是获取所有用户并提供他们的最新评论(如果有的话)。如果没有评论它应该只是为空。也就是说,我想要这个结果:

Name  | Comment          | Posted
------+------------------+-----------
David | Whatever 4       | 2014-01-04
Beth  | Whatever 2       | 2014-01-02
Adam  | Whatever 3       | 2014-01-02
Chris | NULL             | NULL

到目前为止,我所拥有的是类似于此代码的代码(本例简化):

SELECT u.Name AS Name, c.Comment AS Comment, c.Posted AS Posted
FROM User AS u
INNER JOIN Comments AS c ON u.ID = c.UserID
INNER JOIN
(
    SELECT UserID, MAX(Posted) AS Posted FROM Comments AS c2 GROUP BY UserID
) AS c2 ON c2.Posted = c.Posted ORDER BY Posted DESC

这在某种程度上有效,但在我的例子中,我有100个用户和不同的UserID:在评论中有93个帖子。但我只有84行,当我应该有100行,7行空行? 所以,我的问题是:

1)我的查询有什么问题

2)你会怎么做?

2 个答案:

答案 0 :(得分:1)

您的查询是在正确的轨道上,但您需要left join而不是inner join并重新排列加入顺序:

SELECT u.Name AS Name, c.Comment AS Comment, c.Posted AS Posted
FROM User u LEFT JOIN
     (SELECT UserID, MAX(Posted) AS Posted
      FROM Comments c2
      GROUP BY UserID
     ) c2
     ON u.ID = c2.UserID LEFT JOIN
     Comments c
     ON c2.Posted = c.Posted
ORDER BY Posted DESC;

您的查询仅返回至少有一条评论的用户,因此您会错过没有评论的用户。

答案 1 :(得分:1)

这与戈登·林诺夫所说的相同,除了最后一次左联盟。

    SELECT u.Name AS Name, c2.Posted AS Posted,c.Comment
     FROM [User] u LEFT JOIN
     (SELECT UserID, MAX(Posted) AS Posted
      FROM Comments c2
      GROUP BY UserID
     ) c2
     ON u.ID = c2.UserID LEFT JOIN
     Comments c on c2.Posted=c.Posted AND c2.UserId=c.UserId