1. 程式人生 > >group by 和 orede by

group by 和 orede by

同時使用時,先group by再orede by,
所以要獲取最新的資訊,就要先max(time)再group by,

例子

SELECT
    `content`,
    `dialogue_content`.`fuserid` AS `fuserid`,
    `read_new`,
    `add_time`,
    `count`,
    `chat_type` 
FROM
    ( SELECT `content`, `fuserid`, `add_time`, `chat_type` FROM `shopwwi_dialogue` WHERE `touserid`
= '10021' ) `dialogue_content` RIGHT JOIN ( SELECT sum( IF ( isread = 0, 1, 0 ) ) AS `count`, `fuserid`, IF ( min( isread ) = 0, 0, 1 ) AS `read_new`, max( add_time ) AS `max_time` FROM `shopwwi_dialogue` WHERE `touserid` = '10021' GROUP BY fuserid ) dialogue_read ON
`dialogue_content`.`fuserid` = `dialogue_read`.`fuserid` AND add_time = max_time GROUP BY dialogue_content.fuserid ORDER BY add_time DESC