I have two tables, respostas
and respostas_log
, where I store information of the answers in answers and some others that have to go logging in replies_log.
I need in my SELECT to bring only the last log of each response.
Example tables and content:
CREATE TABLE IF NOT EXISTS 'respostas' (
'id' int(11) NOT NULL AUTO_INCREMENT,
'responsavel_id' int(11) NOT NULL,
PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS 'respostas_log' (
'id' int(11) NOT NULL AUTO_INCREMENT,
'respostas_id' int(11) NOT NULL,
'opt_aplicavel' tinyint(1) DEFAULT NULL,
'txt_resposta' text,
'created_at' timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY ('id'),
KEY 'respostas_id' ('respostas_id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO 'respostas' ('id', 'responsavel_id') VALUES
(1, 1),
(2, 3);
INSERT INTO 'respostas_log' ('id', 'respostas_id', 'opt_aplicavel', 'txt_resposta', 'created_at') VALUES
(1, 1, 1, 'Resposta 1 de 1', '2014-05-13 00:00:00'),
(2, 1, 1, 'Resposta 2 de 1', '2014-05-13 00:00:00'),
(3, 1, 0, 'Resposta 3 de 1', '2014-05-13 00:00:00');
And the query I tried
SELECT r.id,
r.responsavel_id,
l.opt_aplicavel,
l.txt_resposta,
max(l.id)
FROM respostas r
LEFT JOIN respostas_log l ON l.respostas_id = r.id
GROUP BY r.id,
r.responsavel_id,
l.opt_aplicavel,
l.txt_resposta
From this example, it would be to bring only the first and last line