If I have the following tables (as an example using PostgreSQL, but could be any other relational database), where car
has two keys (id
and vin
):
create table car (
id int primary key not null,
color varchar(10),
brand varchar(10),
vin char(17) unique not null
);
create table appraisal (
id int primary key not null,
recorded date not null,
car_id int references car (id),
car_vin char(17) references car (vin),
price int
);
I can successfully include c.color
and c.brand
in the select list without aggregating them, since they depend on c.id
:
select
c.id, c.color, c.brand,
min(price) as min_appraisal,
max(price) as max_appraisal
from car c
left join appraisal a on a.car_id = c.id
group by c.id; -- c.color, c.brand are not needed here
However, the following query fails since it doesn't allow me to include c.color
and c.brand
in the select list, even though it does depend on c.vin
(that is a key) of the table.
select
c.vin, c.color, c.brand,
min(price) as min_appraisal,
max(price) as max_appraisal
from car c
left join appraisal a on a.car_vin = c.vin
group by c.vin; -- Why are c.color, c.brand needed here?
Error: ERROR: column "c.color" must appear in the GROUP BY clause or be used in an aggregate function
Position: 18
Example in DB Fiddle.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…