SELECT distinct recipes.*, count(taggings.taggable_id) as tag_count, (Select count(*) FROM taggings WHERE taggings.taggable_id = recipes.id) as tag_total
FROM "recipes"
INNER JOIN "taggings" ON ("recipes"."id" = "taggings"."taggable_id" AND "taggings"."taggable_type" = E'Recipe')
INNER JOIN "tags" ON ("tags"."id" = "taggings"."tag_id")
WHERE (tags.name IN (E'chleb',E'czosnek'))
GROUP BY recipes.id, recipes.title, recipes.instructions, recipes.user_id, recipes.permalink, recipes.created_at, recipes.updated_at, recipes.favorites_count
HAVING (tag_count * 100) / tag_total > 50
ORDER BY tag_total - tag_count, tag_count ASC
LIMIT 10
OFFSET 0
Dostaję błąd: PGError: ERROR: column “tag_count” does not exist. Dotyczy on wszystkich kolumn w których agregowałem jakieś wartości. Wie ktoś gdzie leży problem?
SELECT distinct recipes.*, count(taggings.taggable_id) as tag_count, (Select count(*) FROM taggings WHERE taggings.taggable_id = recipes.id) as tag_total
FROM "recipes"
INNER JOIN "taggings" ON ("recipes"."id" = "taggings"."taggable_id" AND "taggings"."taggable_type" = E'Recipe')
INNER JOIN "tags" ON ("tags"."id" = "taggings"."tag_id")
WHERE (tags.name IN (E'chleb',E'czosnek'))
GROUP BY recipes.id, recipes.title, recipes.instructions, recipes.user_id, recipes.permalink, recipes.created_at, recipes.updated_at, recipes.favorites_count
HAVING (tag_count * 100) / tag_total > 50
ORDER BY tag_total - tag_count, tag_count ASC
LIMIT 10
OFFSET 0
Dostaję błąd: PGError: ERROR: column “tag_count” does not exist. Dotyczy on wszystkich kolumn w których agregowałem jakieś wartości. Wie ktoś gdzie leży problem?[/quote]
Problem jest w tym, że tak nie można zrobić. Kolejność wykonywania zapytania jest taka, że praktycznie obliczenie wartości kolumn to jest praktycznie ostatnia operacja, obliczenie wartości having i group by jest wcześniej, a wtedy nie wiadomo co to jest tag_count.
Upraszczając, zamiast tego:
select sum(a) as x from tab group by a having x > 100;
lepiej zrobić tak:
select sum(a) as x from tab group by a having sum(a) > 100;