Reputation: 31
Is it possible to correlate subquery with an inline view?
Suppose we have simple database that stores information about pet owners.
SELECT p.name,
p.surname,
p.num_of_pets
FROM (SELECT person.id_person id_person,
person.name name,
person.surname surname,
COUNT(DISTINCT person_pets.id_pet) num_of_pets
FROM person
LEFT JOIN person_pets
ON person.id_person=person_pets.id_person) p
WHERE EXISTS(SELECT 1
FROM person p1
WHERE p1.father=p.id_person
OR p1.mother=p.id_person
AND p.num_of_pets > 2)
I know it's quite strange example, but only wanted to show what I mean.
When I run such query I get table or view does not exist
in the place of p table occurrence in subquery.
I suppose I misunderstand how inline views are processed.
Are there any limitations in usage compared to views created with 'with' or 'create view' or to existing tables?
Upvotes: 0
Views: 768
Reputation: 1270653
I suspect that you intend this:
SELECT p.name, p.surname, p.num_of_pets
FROM (SELECT p.id_person, p.name, p.surname,
COUNT(pp.id_person) as num_of_pets
FROM person p LEFT JOIN
person_pets pp
ON p.id_person = pp.id_person
GROUP BY p.id_person, p.name
) p
WHERE EXISTS (SELECT 1
FROM person p1
WHERE (p1.father = p.id_person OR p1.mother = p.id_person) AND
p.num_of_pets > 2
);
I'm not sure why you are getting that particular error, but some notes:
GROUP BY
to be syntactically correct. The COUNT()
without a GROUP BY
should result in an error.COUNT(DISTINCT)
. It has additional overhead, so it is best to get around it.Upvotes: 1