我有两张 table 。想象第一个是一个目录,包含很多文件(第二个表)。
第二个表(文件)包含修改日期。
现在,我想选择所有目录并按修改日期 ASC 对它们进行排序(因此,最新的 修改最上面)。我不想显示该文件夹,而是想显示最旧的 Mofified 文件(因此,修改 DESC,按folder_id 分组)
按修改日期对所有文件进行排序没有问题。
我的查询看起来(简化)如下:
SELECT
f.*,
d.*
FROM
files f
LEFT JOIN
directories d
ON
f.directory_id = d.id
ORDER BY
f.modification_date DESC
这给了我按修改顺序排列的所有文件(最新的最上面) - 现在,我想对文件夹内的文件进行分组,只看到最旧的修改(它们已经“看到”属性,但考虑到这一点并不重要交易,因此一旦看到修改,就会显示第二旧的修改,等等...)
如何按modification_date DESC 对结果进行排序
,同时在分组后按modification_date ASC
对其进行排序?
示例:
目录:
id | name
1 Folder 1
2 Folder 2
文件
id | Name | d_id | modification_datee
1 f1 1 2008-01-01
2 f2 1 2011-01-01
3 f3 2 2013-01-01
4 f4 2 2010-01-01
我想要的结果:
f4 (cause directory 2 contains the NEWEST modification (2013), but f4 is the oldest out of that folder)
f1 (cause directory 1 contains the SECOND newest modification, but f1 is the oldest out of that folder)
有什么建议吗?
最佳答案
一个简单的方法是使用子查询。
示例:
SELECT d.*, ( SELECT f.id FROM files f WHERE f.directory_id=d.id ORDER BY f.modification_date DESC LIMIT 1 ) FROM directories d ORDER BY d.modification_date ASC
但是这只会给你文件的ID,你必须发出另一个请求才能获取每个文件的信息。
另一种方法可能是使用 HAVING 语句(请参阅 http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html )。
通过搜索 HAVING 示例,我发现了这个:http://www.sitepoint.com/forums/showthread.php?535271-Group-by-ID-having-MAX%28date%29-problem 这应该可以帮助您解决问题。
但是您也可以创建这样的临时表:
祝您的项目顺利。
关于mysql - 按日期 ASC 排序,但组内按 DESC 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18195230/