Order within group by?

后端 未结 2 684
不思量自难忘°
不思量自难忘° 2020-12-01 19:19

In my system, I have clients. Clients have programs. I want to display a list of clients, showing their most recent active (if it exists) program.

Thus, we have some

相关标签:
2条回答
  • 2020-12-01 19:55
    SELECT  c.*, p.*
    FROM    clients AS c
    JOIN    programs AS p
    ON      p.id = 
            (
            SELECT  pi.id
            FROM    programs AS pi
            WHERE   pi.client_id = c.id
            ORDER BY
                    pi.close_date=0 DESC, pi.close_date DESC
            LIMIT 1
            )
    

    Thanx should go to @Quassnoi. See his answer in a similar (but more complicated) question: mysql-group-by-to-display-latest-result


    If you update the programs table and set close_date for all records that it is zero to close_date='9999-12-31', then your ORDER BY will be simpler (and the whole query faster with proper indexes):

            ORDER BY
                    pi.close_date DESC
    
    0 讨论(0)
  • 2020-12-01 19:57

    Try this order by clause ...

    ORDER BY client.id, CASE WHEN program.close_date = 0 THEN 0 ELSE 1 END, program.close_date DESC
    
    0 讨论(0)
提交回复
热议问题