由mysql排序和分组无法正常工作

时间:2013-09-22 18:59:52

标签: php mysql sql

<戳这是我想要的

数据库

id | fromm | ontvanger | date | msg | gelezen
--------------------------------------------------
1  | kees  | marc     | time_stamp  | 0
1  | hans  | marc     | time_stamp  | 1
3  | kees  | marc     | time_stamp  | 0
5  | selma | marc     | time_stamp  | 1
6  | kees  | marc     | time_stamp  | 0
7  | kees  | marc     | time_stamp  | 0

这是我想要的GROUP BY fromm

1  | hans  | marc     | time_stamp  | 1
3  | kees  | marc     | time_stamp  | 0
5  | selma | marc     | time_stamp  | 1

$result = mysql_query("SELECT * FROM berichten where ontvanger = '$session->username' 
GROUP BY fromm ORDER BY date DESC
");

显示最新记录,gelezen首先是0

1 个答案:

答案 0 :(得分:1)

SELECT  a.*
FROM    berichten  a
        INNER JOIN
        (
            SELECT  fromm, MAX(date) date
            FROM    berichten
            GROUP   BY fromm
        ) b ON  a.fromm = b.fromm AND
                a.date = b.date
WHERE   a.ontvanger = '$session->username'
ORDER   BY (gelezen = 0) DESC, id

通过子查询,您可以获得每个date最新 fromm。然后将其结果连接回原始表以获取列的其他值。

(gelezen = 0)会产生一个布尔值,如果为真,则会1,否则为0。由于您要根据gelezen = 0对行进行排序,因此对布尔算术的结果应用降序。