Hello, I contacted such a problem, I withdraw from the database

select * from mess where idUser='1' GROUP BY gripname ORDER BY id DESC

It groups, displays everything, but the only thing is that it does not display them in the order of the last id — the first id (ORDER BY id DESC). Help fix this problem.

    1 answer 1

    There is no point in sorting in this case. You should not use in select anything other than the field by which you group and aggregate functions. For example, postgresql deny your request to you, and it will be right.

    Alternatively, you can use something like:

     select max(id), gripname from mess where idUser='1' GROUP BY gripname ORDER BY max(id) DESC 

    In the query above, the DBMS sorts the values ​​according to the maximum id that fell into the grouping. For example, you have a database with values:

     id=1, gripname=a id=4, gripname=b id=5, gripname=a 

    The answer will be output:

     id=5, gripname=a id=4, gripname=b 
    • I knew that the group was blocking С - Sasha Osipov
    • @ SashaOsipov rather subd ignores this sorting as this is an undefined behavior. - Torv
    • thanks, otherwise I couldn’t understand what the hell was going on - Sasha Osipov