SELECT ...
FROM `table_a`
WHERE (some_field=100)
ORDER BY id_a
SELECT ...
FROM `table_a`
LEFT OUTER JOIN `table_b` t1 ON (t1.`id_a`=`table_a`.`id_a`)
WHERE (`table_a`.`id_a`=200)
SELECT `id_b` AS `c`, COUNT(*) AS `s`
FROM `table_c`
WHERE (field=0)
GROUP BY `id_b`
HAVING `table_c`.`id_b` IN (301, 302, 303)
The problem is in last query's HAVING statement. Is it does not use index on id_b field this is significantly slows down the query. Why Yii uses HAVING in this query and is there any workaround to move this into WHERE clause?
Well, using together() and resolving order clause(sorry for that ) still makes 2 queries:
SELECT ...
FROM `table_a`
LEFT OUTER JOIN `table_b` t1 ON (t1.`id_a`=`table_a`.`id_a`)
WHERE (some_field=100)
ORDER BY table_a.id_a
SELECT `id_b` AS `c`, COUNT(*) AS `s`
FROM `table_c`
WHERE (field=0)
GROUP BY `id_b`
HAVING `table_c`.`id_b` IN (301, 302, 303)
The STAT relation always needs a separate query. I don't think you can merge HAVING with WHERE because id_b appears in SELECT and there is an aggregation involved. (it may work on MySQL, but not on PostgreSQL)