我有以下(简化的)数据库架构:
CREATE TABLE IF NOT EXISTS `wm_renderings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`formula_id` int(11) NOT NULL,
`creation_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`svg` text COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`),
KEY `formula_id` (`formula_id`)
);
其中 formula_id
是外键。
我想获取每个 formula_id
的最新渲染。但是当我写
SELECT `id`, `formula_id`, `svg`
FROM `wm_renderings`
GROUP BY `formula_id`
ORDER BY `creation_time` DESC
我会为每个 Formula_id 获得“随机”渲染。
我的方法是获取所有公式 ID,然后为每个公式 ID 发送查询:
SELECT `id`, `formula_id`, `svg`
FROM `wm_renderings`
WHERE `formula_id` = 42
ORDER BY `creation_time` DESC
LIMIT 1
但是,这会产生很多查询。
我可以只用一个查询得到相同的结果吗?
最佳答案
获取每个组的max
/latest
的方法有多种,其中一种方法是使用left join
select t1.* from wm_renderings t1
left join wm_renderings t2 on t1.formula_id = t2.formula_id
and t1.creation_time < t2.creation_time
where t2.id is null
这是它的文档
http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html
左连接和不相关子查询被认为在性能方面更好。
关于mysql - 如何通过一个 SQL 查询获取每个外键 ID 的最新数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27398751/