Estou trabalhando em um aplicativo php e preciso recuperar o registro mais recente de uma tabela mysql. Abaixo está o design da tabela e os dados de amostra.
Então o critério é:
classifique por DESC presente e, em seguida, start_date DESC
Saída esperada
Estou pensando como abaixo, existe alguma solução melhor sobre isso?
SELECT *
FROM `experience` r
JOIN (
SELECT MAX(start_date) as date,
resume_id
FROM `experience`
WHERE present = 1
group by resume_id
)r2 ON r.resume_id = r2.resume_id
AND r.present = 1
AND r.start_date = r2.date
UNION
SELECT *
FROM `experience` r
JOIN (
SELECT MAX(start_date) as date,
resume_id
FROM `experience`
WHERE present = 0
group by resume_id
) r2 ON r.resume_id = r2.resume_id
AND r.present = 0
AND r.start_date = r2.date
WHERE NOT EXISTS (SELECT 1
FROM `experience`
WHERE present = 1
AND r.resume_id = resume_id
)
// took around 11-20 seconds to process above query on total 499,000 records
Explicar a consulta
ATUALIZAR:
http://sqlfiddle.com/#!9/bc5a12/1
CREATE TABLE `experience`(
`id` int(11) NOT NULL,
`resume_id` varchar(9) DEFAULT NULL,
`company_name` varchar(12) DEFAULT NULL,
`start_date` date DEFAULT NULL,
`end_date` date DEFAULT NULL,
`present` varchar(7) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `experience`(
`id`,
`resume_id`,
`company_name`,
`start_date`,
`end_date`,
`present`)
VALUES
(1, '1', 'abc', '2009-01-01', '2009-12-31', '0'),
(2, '1', 'def', '2010-01-01', '2012-12-31', '0'),
(3, '1', 'ghi', '2013-01-01', '0000-00-00', '1'),
(4, '2', 'abc', '2009-01-01', '2009-12-31', '0'),
(5, '2', 'def', '2010-01-01', '2012-12-31', '0'),
(6, '2', 'ghi', '2013-01-01', '2016-01-01', '0'),
(7, '3', 'abc', '2009-01-01', '2009-12-31', '0'),
(8, '3', 'def', '2017-01-01', '0000-00-00', '1'),
(9, '3', 'ghi', '2010-01-01', '0000-00-00', '1');
ALTER TABLE `experience`
ADD PRIMARY KEY (`id`);
Como uma piada (mas deve funcionar mesmo assim):
violino