E
E
ellz2019-03-14 14:14:24
PostgreSQL
ellz, 2019-03-14 14:14:24

Why is there a "column must appear in the GROUP BY clause or be used in an aggregate function" error?

There are two tables:
images:

create table images
(
  id        serial      not null
    constraint images_pk
      primary key,
  image_url varchar(60) not null,
  autor_id  integer     not null,
  views     integer,
  rating    numeric
);

and votes:
create table votes
(
  id       serial  not null
    constraint votes_pk
      primary key,
  image_id integer not null,
  user_id  integer not null,
  value    integer not null
);

and here is the query:
select image_url, (select avg(votes.value))
                from images
                      inner join votes on votes.image_id = images.id
                group by image_url
                order by views asc

Which should pull the link to the image and its average rating from the votes table. Since image_url is repeated in the table with votes, I did group by image_url, but I get an error
column "images.views" must appear in the GROUP BY clause or be used in an aggregate function
. What could be the problem?
I tried to set different values ​​in gprup by, but the error still remains, only the field in it changes. For example:
group by images.views-column "images.image_url" must appear in the GROUP BY clause or be used in an aggregate function

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2019-03-14
@ellz

This error is related to

...
order by views asc

try
...
order by sum(views) asc

A
Anatoly, 2019-03-14
@AnatolTh

select 
   image_url, 
   avg(votes.value) as myavg
from images

inner join votes on votes.image_id = images.id
group by image_url
order by myavg asc

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question