user7713452
user7713452

Reputation: 77

MySQL GROUP BY altering with ORDER BY

Database table image I have the table above and I want to run a MySQL query to group rows where noteId, dataId, and type have the same value.

$query = mysqli_query($con, "SELECT * FROM table WHERE userTo = '1' GROUP BY noteId, dataId, type ORDER BY id DESC");

Now I believe this query above should do the grouping and return the last row in each group. But instead I am getting the first row in each group.

For example rows 13, 14 and 16 are grouped together. So I want row 16 to be returned by doing ORDER BY id DESC but instead am getting row 13.

Please can anyone help me?

Upvotes: 1

Views: 302

Answers (1)

Passionate Coder
Passionate Coder

Reputation: 7294

You can try this

 SELECT * FROM (SELECT * FROM  table ORDER BY id DESC) t
 WHERE t.userTo = '1' GROUP BY t.noteId, t.dataId, t.type

Upvotes: 2

Related Questions