L
L
Lexxtor2016-08-03 13:57:40
MySQL
Lexxtor, 2016-08-03 13:57:40

How to get the last comment of each user without a comment ID?

Table with data:

CREATE TABLE `comments` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `comments` (`id`, `user_id`, `text`) VALUES
(1,	1,	'hello'),
(2,	1,	'omg'),
(3,	1,	'last'),
(4,	2,	'ko ko ko');

Request:
SELECT  max(id), user_id, text
FROM `comments`
GROUP BY user_id

How to change the query so that it displays the same thing, but without the first column (only user_id and text).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lexxtor, 2016-08-03
@Lexxtor

select c0.user_id, c0.text
from `comments` as c0
left join `comments` as c1
    on c1.user_id = c0.user_id and c1.id > c0.id
where c1.id is null;

Also, the query in the question returns an incorrect result.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question