I need to get a list of Articles sorted by the latest Comment from a related table joined on article.id = message.article_id using Kohana ORM. I managed to build a query that GROUPS and only then ORDERS:
SELECT *
FROM `articles`
LEFT JOIN `comments` ON ( `articles`.`id` = `comments`.`article_id` )
GROUP BY `comments`.`item_id`
ORDER BY `datetime` DESC
The query I am trying to build is:
SELECT * FROM `articles` LEFT JOIN
(SELECT article_id, MAX(datetime) as datetime FROM comments GROUP BY (article_id))
AS b ON `articles`.`id` = b.`article_id`
ORDER BY datetime
I have no idea how to rewrite it into Kohana ORM... (and I can't avoid ORM because there is a ton of code that depends on it)
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `comments` ADD INDEX `comments_idx_article_id_item_id` (`article_id`,`item_id`);
SELECT
*
FROM
`articles`
LEFT JOIN
`comments`
ON (
`articles`.`id` = `comments`.`article_id`
)
GROUP BY
`comments`.`item_id`
ORDER BY
`datetime` DESC