[Solved] Kohana ORM, rewriting an ORDER BY and GROUP BY query
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Kohana ORM, rewriting an ORDER BY and GROUP BY query

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)

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `comments` ADD INDEX `comments_idx_article_id_item_id` (`article_id`,`item_id`);
The optimized query:
SELECT
        * 
    FROM
        `articles` 
    LEFT JOIN
        `comments` 
            ON (
                `articles`.`id` = `comments`.`article_id`
            ) 
    GROUP BY
        `comments`.`item_id` 
    ORDER BY
        `datetime` DESC

Related Articles



* original question posted on StackOverflow here.