I would like to select the most recent record for every group, but I have problems because I got an error
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'query1.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by```
I have two joined tables: users and messages. So, users can send messages to each other, and I would like to select for given user the last message from his contacts.
I managed to find all contacts for specific user using CASE WHEN:
SELECT * FROM
 (
 SELECT *,
     CASE
        WHEN idFrom = 18 THEN idTo
        WHEN idTo = 18 THEN idFrom
        ELSE ''
    END AS contact
 FROM messages 
 WHERE idFrom = 18 OR idTo = 18
 ) query1
INNER JOIN users ON users.user_id = query1.contact
but I don't know how to group these contacts.
Expected result is:
I prepared a data set...
CREATE TABLE `users` (
  `user_id` int(11) NOT NULL,
  `firstName` varchar(50) NOT NULL,
  `lastName` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `users` 
(`user_id`, `firstName`, `lastName`) 
VALUES
(18, 'Bart', 'Simpson'),
(33, 'Marge', 'Simpson'),
(45, 'Homer', 'Simpson'),
(99, 'Lisa', 'Simpson');
CREATE TABLE `messages` (
  `id` int(11) NOT NULL,
  `idFrom` int(11) DEFAULT NULL,
  `idTo` int(11) DEFAULT NULL,
  `message` varchar(500) DEFAULT NULL,
  `messageDate` datetime NOT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for table `messages`
--
ALTER TABLE `messages`
  ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for table `messages`
--
ALTER TABLE `messages`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34;
COMMIT;
INSERT INTO messages
 (idFrom, idTo, message, messageDate)
 VALUES 
 (18, 33, 'Hello Marge', '2000-05-05 16:29:25'),
 (33, 18, 'Hello Bart', '2001-05-05 16:29:25'),
 (18, 99, 'Hello Lisa', '2002-05-05 16:29:25'),
 (99, 45, 'Hello Homer', '2003-05-05 16:29:25'),
 (18, 99, 'Hello Lisa Again!!!', '2004-05-05 16:29:25'),
 (33, 18, 'Hello Bart Again', '2005-05-05 16:29:25');
select version();
...and Fiddle of same




 
    