doucang9673 2013-09-22 18:59
浏览 36
已采纳

由mysql排序和分组不工作[关闭]

oke this is wat i want

Database

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

this is wat i want 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
");

Show the latest record and gelezen is 0 first

  • 写回答

1条回答 默认 最新

  • doufusi2013 2013-09-22 19:04
    关注
    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
    

    The subquery lets you get the latest date for each fromm. The result of it is then joined back on the original table to get the other values of the columns.

    (gelezen = 0) results in a boolean value that if it is true will give 1 otherwise 0. Since you want to order the row based on gelezen = 0, apply a descending order on the result of boolean arithmetic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含