2011-02-04 108 views
0

我有兩個表:UsersFilesMySQL中的右外連接

用戶表有10行,文件表有450行,其中有一列用於用戶標識(UserID)。

我想查詢他們上次下載的所有人員和文件的列表。文件表有LastDownloadTime字段,其​​類型爲DateTime

這是我的SQL查詢;

Select 
    Users.Name , Files.Name 
FROM Users 
RIGHT OUTER JOIN Files on Users.ID = (
    Select Files.UserID 
    FROM Files 
    ORDER BY LastDownloadTime DESC Limit 1 
) 

上面的查詢返回所有用戶和文件。什麼應該是正確的查詢呢?

+0

你試過了嗎? 選擇Users.Name,Files.Name FROM用戶RIGHT OUTER JOIN Users.ID上的文件= Users.UserID ORDER BY Files.LastDownloadTime DESC Limit 1) – B4NZ41 2011-02-04 12:24:23

回答

2

你可以這樣做:

Select 
    u.Name, 
    (Select f.Name from Files f where u.ID = f.ID order by LastDownloadDate LIMIT 1) 
FROM Users u 
1

看到這些:

SELECT Users.Name , Files.Name 
    FROM Users 
    RIGHT OUTER JOIN 
    (SELECT Files.Name 
     FROM Files 
     INNER JOIN 
      (SELECT TOP 1 Files.UserID ,Max(LastDownloadTime) as LastDownloadTime 
        FROM Files 
        ORDER BY LastDownloadTime DESC,Files.UserID ) as f2 
    ON Files.UserID = f2.UserID AND Files.LastDownloadTime = f2.LastDownloadTime 
    ) as f ON Users.ID = f.UserID 
+0

「TOP」不會在MySQL中工作 – 2011-02-04 12:32:56

+0

我試過了這個查詢顯示現在只有一個用戶和所有文件:) – atromgame 2011-02-04 12:40:10

0

你確定有關的權利的加入?你的問題似乎不同。

Select 
    Users.Name 
    ,f2.Name 
FROM 
    Users 
     JOIN (SELECT userid, MAX(lastdownloadtime) AS latest FROM Files GROUP BY userid) f1 ON f1.userid = Users.id 
     JOIN Files f2 ON (Users.ID = f2.userid AND f2.lastdownloadtime = f1.latest);