dongwuwei0718 2012-11-20 09:20
浏览 45
已采纳

如何在一个请求中为每种类型选择MAX

I use mysql 5.1.

This is my DB schema :

id     user_id     type     created_at
1       32          X       2012-11-19
2       32          Y       2012-11-18
3       30          X       2012-11-16
4       32          Z       2012-11-17
5       31          Y       2012-11-13
6       32          Z       2012-11-9

I want that my SQL query returns the user_id, type, and the lastest created_at for each type. I tried to make this request: SELECT max(type) FROM notification WHERE user_id=34 ORDER BY type but it returns only the latest created_at.

  • 写回答

5条回答 默认 最新

  • dqtiober37522 2012-11-20 09:26
    关注

    You cannot do this in really simple query because GROUP BY (which you are missing by the way in your query) doesn't guarantee that it won't return values mixed from multiple rows.

    SELECT * FROM notifications AS t1
    INNER JOIN (
        SELECT type, MAX(`created_at`) AS max_created_at
        FROM notification
        WHERE user_id=34
        GROUP BY `type`
    ) AS t2
        ON t1.type = t2.type
            AND t1.created_at = t2.max_created_at
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址