I've seen couple of implementations to my issue around SO, but still can't tweak this to my needs.
// table:
CREATE TABLE `chat_msgs` (
`id` int(11) NOT NULL,
`chat_id` int(11) NOT NULL,
`user_to` varchar(70) NOT NULL,
`user_from` varchar(70) NOT NULL,
`body` varchar(255) NOT NULL,
`msg_time` datetime NOT NULL,
`viewed` enum('0','1') NOT NULL DEFAULT '0' )
ENGINE=InnoDB DEFAULT CHARSET=utf8;
// dummy chat data:
INSERT INTO `chat_msgs` (`id`, `chat_id`, `user_to`, `user_from`, `body`, `msg_time`, `viewed`) VALUES
(46, 1, '40', '39', '我们商谈订单细节,好码?', '2018-03-05 01:06:38', '1'),
(47, 1, '40', '39', '45', '2018-03-05 01:06:56', '1'),
(48, 1, '39', '40', 'OK?', '2018-03-05 08:12:34', '0'),
(49, 2, '39', '211', 'jk', '2018-03-05 08:27:05', '1'),
(50, 2, '211', '39', 'hj', '2018-03-05 08:27:12', '1'),
(66, 2, '39', '211', 'fe', '2018-03-06 16:44:03', '0'),
(67, 3, '39', '160', 'sdfs sdfg fg', '2018-03-08 16:44:06', '0'),
(68, 3, '39', '160', 'are yoy here my friend?', '2018-03-09 08:44:06', '0');
Target: rows, where per each unique chat_id I have ONE LATEST (by time) row, containing: chat_id, user_to (user, to whom msg was sent), user_from (who sent msg), body (which is the message itself) and max(msg_time).
Essentially, it should output the latest chat msg logged-in user had with any other user.
I came up with:
SELECT * FROM (SELECT chat_id,user_to,user_from,body,max(msg_time) FROM chat_msgs GROUP BY chat_id) t1 JOIN (SELECT chat_id,count(viewed) unviewed FROM chat_msgs WHERE viewed='0' AND user_to='39' group by chat_id) t2 on t1.chat_id=t2.chat_id
which does most part, except for the fact it does not return the latest 'body'.
I understand I gotta fit in a sub query for selecting right body, but somehow cant get to it. Thanks