There are a couple of problems with your query.
- You use a
LEFT OUTER JOIN
, yet in theWHERE
clause you sayAND "items_categories"."cat_id" IN(1)
which makes theOUTER JOIN
effectively anINNER JOIN
because each row in"items"
that has no corresponding record in"items_categories"
will returnNULL
for"items_categories"."cat_id"
and thus get eliminated by theWHERE
clause - There quite a bit of blogs that indicate that
SQL_CALC_FOUND_ROWS
can have a negative effect on performance; are you sure you really need it ? - I'm confused you can do
GROUP BY "items"."id"
and then follow it withORDER BY "items"."artist" ASC, "items"."name" ASC
. I'm used to MSSQL and this simply will not compile!?! - I'm assuming that the the GROUP BY is there because the JOIN would cause 'doubles' as multiple records in "items"categories" might fit the requirements. If so, you should rather use a
WHERE EXISTS
construction instead of doing the actual JOIN and then GROUPing everything again to get rid of them. (same story for DISTINCT which is just a fancy GROUP BY anyway)
Hence, I would suggest this:
SELECT "items"."id"
FROM "items"
WHERE "items"."id" > 0
AND "items"."hidden" = 0
AND "items"."deleted" = 0
AND EXISTS ( SELECT *
FROM "items_categories"
WHERE "items_categories"."item_id" = "items"."id"
AND "items_categories"."cat_id" IN (1) )
ORDER BY "items"."artist" ASC, "items"."name" ASC
LIMIT 0, 100;
(which --more or less-- would also compile in MSSQL =)