Write a SQL query to MySQL DBMS, which will select user names and their last comments from the database (one comment per user), with the following table structure:
CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `balance` decimal(10,2) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 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 AUTO_INCREMENT=1 ;
I had this solution here, but it doesn’t fit a bit. It only displays users who have a comment. It is necessary to display all users with their last comment , and if anyone has a comment, the line “no comments” was returned.
SELECT uc.name, c.text FROM comments c, ( SELECT u.id, u.name, MAX(c.id) as last_cid FROM users u LEFT JOIN comments c ON c.user_id = u.id GROUP BY u.id )uc WHERE c.user_id = uc.id AND c.id = uc.last_cid";
left join
to your subquery? those. something likeselect name, text from comments left join (вложенный запрос)
- Bald