I am novice in MySQL and I have a problem with sorting two tables.
This SQL is about sorting newest comments on books, but I am getting these books sorted by first comments on them, not on latest.
SELECT b.*, c.date_added as date FROM books b
LEFT JOIN comments c ON (b.id = c.book_id)
GROUP BY b.id
ORDER BY date DESC
LIMIT 5
CREATE TABLE IF NOT EXISTS `books` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`caption` varchar(255) COLLATE utf8_bin NOT NULL,
`author` varchar(255) COLLATE utf8_bin NOT NULL,
`pages` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`filename` varchar(255) COLLATE utf8_bin NOT NULL,
`description` text COLLATE utf8_bin NOT NULL,
`date_added` datetime NOT NULL,
`publisher` varchar(255) COLLATE utf8_bin NOT NULL,
`price` decimal(10,2) NOT NULL,
`times_sold` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`book_id` int(11) NOT NULL,
`author` varchar(255) COLLATE utf8_bin NOT NULL,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`body` text COLLATE utf8_bin NOT NULL,
`date_added` datetime NOT NULL,
`approved` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Thank you for your time.
This should work out. You are specifying the group on b.id, but since you are multiple comments for each book, you need an aggregate function on c.date_added. In this case you can use MAX to show the most recent comment date.