Pamroni
Pamroni

Reputation: 1

Beginner MySQL issues with invalid use of group function

I've been googling around and can't seem to find how to fix this. I'm currently using MySQL and am trying to run this

SELECT song_id FROM ‘played_songs’ WHERE id=MAX(id)

When I run this, I get the error message

1111 - Invalid use of group function

Does anyone know what I am doing wrong here? For reference, I'm trying to get the latest row's song_id in a pre-existing database. The ID increments so the latest value is the max ID in the column. When I get that column, I would like to get it's song_id in that same row.

Sorry if this is a super basic question, I've never done this before.

Thanks!

Upvotes: 0

Views: 64

Answers (2)

Bleach
Bleach

Reputation: 561

You need to use a "Having" instead of a "where". A Having is used when you are operating on a previous calculation (getting max id is a calculation mysql has to make). I would write like this.

SELECT song_id, MAX(id) as 
max_id FROM ‘played_songs’ 
HAVING max_id=id

Upvotes: -1

RainDev
RainDev

Reputation: 1128

you can't use max in where clause, try this:

SELECT song_id FROM played_songs WHERE id=(SELECT max(id) FROM played_songs)

but better solution is:

SELECT song_id FROM played_songs ORDER BY id DESC LIMIT 1;

Upvotes: 5

Related Questions