Ondrej
Ondrej

Reputation: 2397

Grouping results in a specific order

I'm stuck with a MySQL query. At first, I thought it would be an easy job, but it's turned into something I just can't get over.

I have a table such as:

ID_USER  ID_LESSON  TITLE
   1        1       Maths
   1        2       Geography
   1        3       History
   2        4       Spanish
   2        5       Maths
   2        6       English

I need to get result such as:

ID_USER  ID_LESSON  TITLE
   1        2       Geography
   2        6       English

Basicly, what I need to get is one row for each user where is subject title ordered ascendantly.

I tried a query like

SELECT id_user, id_lesson, title FOM table 
GROUP BY id_user ORDER BY title ASC

But the problem was, that even if I got just one row for each user, the title in the result was not right (because when I used GROUP BY command, the result was ordered by id_lesson)

I have a feeling that the solution maybe quite simple but I cant break it down.

I'll be happy for any suggestions.

Thank you!

Upvotes: 0

Views: 75

Answers (1)

Marco
Marco

Reputation: 57573

Try this:

SELECT t1.* FROM your_table t1
WHERE t1.title = 
    (SELECT title FROM your_table
     WHERE id_user = t1.id_user
     ORDER BY title
     LIMIT 1)

Upvotes: 3

Related Questions