First off take a look at your data model, it has a couple fundamental problems.
In CAR_PERSONS_RELATIONS table you are attempting to create a FK on car_type. However, to do so car_type would have to be
unique in the car table. From the documentation section 5.4.5. Foreign Keys .
A foreign key constraint specifies that the values in a column (or a group of columns) must match the values
appearing in some row of another table. We say this maintains the
referential integrity between two related tables. ... A foreign key
must reference columns that either are a primary key or form a unique
constraint.
But this would there could only be 1 car for a given type in the
table.
Now look at the PERSON table. This table contains a FK to car_id, thus establishing a M:1 to CAR. Basically this relationship
says "A person can own only 1 car, but a car can be owned by many persons". Your description and table name indicate
this is NOT the relationship you are trying to define.
Correcting requires the following changes:
- Add car_id to CAR_PERSON_RELATIONS.
- Remove car_id from PERSON.
- Remove car_type from CAR_PERSON_RELATIONS.
- Redefine CAR_PERSON_RELATIONS PK to car_id, person_id.
Alternately
leave the surrogate PK and create UK on car_id,person_id).
- Create the FKs from CAR_PERSON_RELATIONS to CAR and PERSON.
Revised Model
create table person (
id serial
,name varchar(300) not null
,constraint person_pk primary key (id)
);
create table car (
id serial
,type varchar(50) not null
,constraint car_pk primary key (id)
);
create table car_person_relations (
car_id integer
,person_id integer
,constraint car_person_relations primary key (car_id, person_id)
,constraint car_person_relations_2_car_fk
foreign key (car_id)
references (car.id)
,constraint car_person_relations_2_person_fk
foreign key (person_id)
references (person.id)
):
And then the necessary query becomes:
select cpr.car_type, count(*) as num_persons
from car_person_relations cpr
join car c
on cpr.car_id = c.id
group by cpr.car_type
order by count(*) desc
limit 1;