R
R
Ruslan Absalyamov2019-04-07 19:48:48
SQL
Ruslan Absalyamov, 2019-04-07 19:48:48

How to make a correct query on related tables grouping and sorting?

I have a ticket_themes room table and a ticket_message message table. I need to get the room and the last message in it.
My example does not work, I do not understand how to do it right

SELECT * FROM ticket_themes ticket LEFT JOIN ticket_message tm on ticket.id = tm.theme_id WHERE ticket.user_id = 69625 ORDER BY tm.created_at DESC

If in this case I add GROUP BY to the room id, I get an error
[42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY ticket.id' at line 1

How to make the right request

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fagi, 2019-04-08
@Fagi

Perhaps the problem is that the select contains an asterisk and both tables have the same columns. Try to manually specify the names of the columns you want to get.

SELECT ticket.theme_text, tm.message_text FROM ticket_themes ticket LEFT JOIN ticket_message tm on ticket.id = tm.theme_id WHERE ticket.user_id = 69625 ORDER BY tm.created_at DESC

A
Androgen13, 2019-04-08
@Androgen13

SELECT *
FROM (SELECT ticket.name as ticket_name, tm.text as message_text, tm.created_at as message_dt, ROW_NUMBER() OVER(PARTITION BY ticket.user_id ORDER BY tm.created_at DESC, tm.id DESC) AS rn
  FROM 
    ticket_themes ticket 
    LEFT JOIN ticket_message tm on ticket.id = tm.theme_id 
  WHERE ticket.user_id = 69625 ) t
WHERE t.rn = 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question