I've been experiencing problems when selecting images by multiple tags, and now I got this exception:
Error: Error: PGError: ERROR: canceling statement due to statement timeout : SELECT COUNT(*) FROM posts p JOIN posts_tags rpt0 ON rpt0.post_id = p.id AND rpt0.tag_id = (SELECT id FROM tags WHERE name = E'tag1') JOIN posts_tags rpt1 ON rpt1.post_id = p.id AND rpt1.tag_id = (SELECT id FROM tags WHERE name = E'tag2') JOIN posts_tags rpt2 ON rpt2.post_id = p.id AND rpt2.tag_id = (SELECT id FROM tags WHERE name = E'tag3') WHERE true AND p.status <> 'deleted'
To me, this query is inefficient. Why join the same table posts_tags three times, each of which is formed by an additional select? One additional select would be enough, if it is needed at all. Consider this statement (I'm leaving true because it means nothing):
SELECT COUNT(*) FROM posts p JOIN posts_tags rpt0 ON rpt0.post_id = p.id AND rpt0.tag_id = (SELECT id FROM tags WHERE name = E'tag1' or name = E'tag2' or name = E'tag3') WHERE true AND p.status <> 'deleted'
Or this:
SELECT COUNT(*) FROM posts p JOIN posts_tags rpt0 ON rpt0.post_id = p.id AND rpt0.tag_id = (SELECT id FROM tags WHERE name in (E'tag1', E'tag2', E'tag3')) WHERE true AND p.status <> 'deleted'
I understand that often, queries are generated automatically, but sometimes it's just worth it to manually code them. :)
Updated by miton