从一对多关系中获取最新记录

时间:2018-12-10 16:10:10

标签: mysql sql

正如我在标题中所述,具有以下架构:

CREATE TABLE IF NOT EXISTS `services` (
  `id` int(6) unsigned NOT NULL,
  `description` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `services` (`id`, `description`) VALUES
  ('1', 'Water flood from kitchen'),
  ('2', 'Light switch burnt');


CREATE TABLE IF NOT EXISTS `visits` (
  `id` int(6) unsigned NOT NULL,
  `date` DATETIME NOT NULL,
  `description` varchar(200) NOT NULL,
  `worker` varchar(200) NOT NULL,
  `services_id` int(6) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `visits` (`id`, `date`, `description`, `worker`, `services_id`) VALUES
  ('1', '2018-12-10 16:00:00', 'Find and stop leak', 'Thomas', '1'),
  ('2', '2018-12-11 09:00:00', 'Change broken pipe', 'Bob', '1'),
  ('3', '2018-12-10 19:00:00', 'Change light switch', 'Alfred', '2'),
  ('4', '2018-12-11 10:00:00', 'Paint wall blackened by shortcircuit', 'Ryan', '2');

对于每种服务,我都需要按日期进行最近的访问。

在此示例中,我将得到:

'1', '2018-12-10 16:00:00', 'Find and stop leak', 'Thomas', '1'
'3', '2018-12-10 19:00:00', 'Change light switch', 'Alfred', '2'

你会怎么做?我正在努力寻求解决方案。

这是SQLFiddle:

http://sqlfiddle.com/#!9/3ca219

1 个答案:

答案 0 :(得分:2)

我建议一个相关的子查询:

select v.*
from visits v
where v.date = (select max(v2.date)
                from visits v2
                where v2.services_id = v.services_id
               );

使用visits(services_id, date)上的索引,它应该比其他方法快或快。