MySQL - 查找每个用户的最新上传内容

时间:2014-03-13 23:28:27

标签: php mysql

我有以下files表,其中为多个用户存储文件(该表仅显示1个用户的文件)。

+--------+----------+----------+------------------------------+
| fileID | fileName | folderID | userID | uploadDate          |        
+--------+----------+----------+--------+---------------------+
| 1      | file1    | 1        | 1      | 2014-02-03 12:00:00 |
| 2      | file2    | 2        | 1      | 2014-01-05 12:00:00 |
| 3      | file3    | 3        | 1      | 2014-01-08 12:00:00 |
| 4      | file4    | 2        | 1      | 2014-01-04 12:00:00 |
| 5      | file5    | 1        | 1      | 2014-01-07 12:00:00 |
| 6      | file6    | 3        | 1      | 2014-01-09 12:00:00 |
+--------+----------+----------+--------+---------------------+

我想按日期查找为每个文件夹上传的最新文件。 结果应该是这样的......

+--------+----------+----------+------------------------------+
| fileID | fileName | folderID | userID | uploadDate          |        
+--------+----------+----------+--------+---------------------+
| 2      | file2    | 2        | 1      | 2014-03-05 12:00:00 |
| 5      | file5    | 1        | 1      | 2014-03-07 12:00:00 |
| 6      | file6    | 3        | 1      | 2014-03-09 12:00:00 |
+--------+----------+----------+--------+---------------------+

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

啊,这对SQL来说是一件非常困难的事情。我最好的解决方案是创建一个临时表,然后加入它:

CREATE TABLE Table1     (fileID int,fileName varchar(5),folderID int,userID int,uploadDate datetime) ;

INSERT INTO Table1
    (`fileID`, `fileName`, `folderID`, `userID`, `uploadDate`)
VALUES
    (1, 'file1', 1, 1, '2014-02-03 12:00:00'),
    (2, 'file2', 2, 1, '2014-01-05 12:00:00'),
    (3, 'file3', 3, 1, '2014-01-08 12:00:00'),
    (4, 'file4', 2, 1, '2014-01-04 12:00:00'),
    (5, 'file5', 1, 1, '2014-01-07 12:00:00'),
    (6, 'file6', 3, 1, '2014-01-09 12:00:00')
;

create temporary table last_files (
  fileID int, fileName varchar(5), folderID int, userID int , 
  unique key( folderID, userID )
);

REPLACE INTO last_files ( fileID, fileName, folderID, userID ) 
select fileID, fileName, folderID, userID 
from Table1 order by uploadDate asc;

select * from last_files;

它使用临时表来整理结果,然后连接回原始表,而不是子查询。这是我过去在大型桌子上使用的模式,效果非常好。

如果您正在寻找特定用户,则可以SORT BY uploadDate DESC LIMIT 1代替,但这显然是有限的。