Order within group by?

假装没事ソ 提交于 2019-11-27 09:06:44
ypercubeᵀᴹ
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
JSR

Try this order by clause ...

ORDER BY client.id, CASE WHEN program.close_date = 0 THEN 0 ELSE 1 END, program.close_date DESC
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!