2014-10-07 64 views
1

我想實現的真的很基本,我找到了一個類似的解決方案here,但是我無法使它與我正在使用的MS SQL Compact一起工作。從其他表中選擇MAX值,如果有的話

可以說我有這些表:

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)你會怎麼做呢?

回答

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; 

您的查詢只返回至少有一個評論的用戶,那麼你就錯過用戶沒有評論。

+0

那麼,我試着把它們轉向所有的方向,但結果的錯誤數目。 ;)給了相同數量的職位。 – gubbfett 2014-10-07 11:56:27

+0

延遲編輯;我錯過了你把兩個都放在左邊,那給了我數百行。但是,是的,一些如何我的查詢是不正確的,因爲它不給我所有100個用戶。 – gubbfett 2014-10-07 12:12:05

+0

@gubbfett。 。 。我可以看到這會發生。 '加入'需要按照正確的順序。 – 2014-10-07 12:15:35

1

這與Gordon Linoff所說的除了最後一次加入之外都是一樣的。

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 
相關問題