MySQL中的右外连接

时间:2011-02-04 12:17:53

标签: mysql join

我有两个表:UsersFiles

用户表有10行,文件表有450行,其中有一列用于用户ID(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
)

以上查询返回所有用户和文件。什么应该是正确的查询?

3 个答案:

答案 0 :(得分:2)

你可以这样做:

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

答案 1 :(得分: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

答案 2 :(得分: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);