E
E
Eugene2015-09-30 20:27:40
SQL
Eugene, 2015-09-30 20:27:40

A selection of recent comments?

Help a beginner solve this problem:
There are two tables:
users
----------------------
id | name
1 | name1
2 | name2
3 | name3
and comments
-----------------------
id | user_id | text1
| 1 | com1
2 | 2 | com2
3 | 1 | com3
4 | 3 | com4
5 | 2 | com5
6 | 3 | com6
You need to select the name and last comment of all users in one query.
Those. should be:
name1 | com3
name2 | com5
name3 | com6
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Filimonov, 2015-09-30
@epodik

SELECT U.name, C.text
FROM comments C
INNER JOIN users U
ON C.user_id = U.id
AND C.id = (
    SELECT id 
    FROM comments 
    WHERE user_id=U.id
    ORDER BY id DESC
    LIMIT 1
)

If one of the users does not have comments, they will not be in the sample. RIGHT JOIN might fix this. If you enter a column with a date, then there will be a similar query with a subquery, but only in the subquery there will be an aggregation by user_id and a maximum date selection. You can do it somehow, I think, but I don’t see the point, it’s a completely normal request.
ps It's good manners in such questions to post the code (and query attempts) on sqlfiddle and add the phrase "totally lazy and wanting someone to do everything for me" before the word "beginner".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question