一、问题
GROUP BY分组后取最新时间的一条记录的SQL的解决方案。
二、解决方案
首先对资源表数据进行排序(多表)
SELECT a1.*, a2.a2id FROM table1 a1 LEFT JOIN table2 a2 ON a1.a1id = a2.a2id WHERE a1.time ORDER BY a1.time desc
然后组合以上SQL生成的临时表进行嵌套查询(多表)
SELECT w.* FROM ( SELECT a1.*, a2.a2id FROM table1 a1 LEFT JOIN table2 a2 ON a1.a1id = a2.a2id WHERE a1.a1time ORDER BY a1.a1time desc ) w GROUP BY w.a1id
另外在查询时,有一篇文章内在临时表查询时加入了having 1作为条件,经测试,取消后得到的结果是相同的,各位可以在使用时自定义测试
SELECT w.* FROM ( SELECT a1.*, a2.a2id FROM table1 a1 LEFT JOIN table2 a2 ON a1.a1id = a2.a2id WHERE a1.a1time HAVING 1 ORDER BY a1.a1time desc ) w GROUP BY w.a1id
临时表内的a2.id可替换为a2.*作为临时表w的多数据条件