doulu1867 2014-03-08 19:55
浏览 52
已采纳

如何使用mysql选择多个最大值

I have a table recipients like this

Id    user_id   thread_id
_________________________
1     1215      3833
2     1215      3833
3     1862      3833
........................

10    1215      3834
11    1862      3834

And I have an array with some values(user_id). For each value, which is my user_id-s I want to select maximum thread_id. For single given value(for example 1215) I can get the value with this simple query

query = "SELECT MAX(thread_id) FROM recipients WHERE user_id = 1215 "

But I can't use this to get all maximum thread_id-s from table when I will try to write something like this

query = "SELECT MAX(thread_id) FROM recipients WHERE user_id IN (1215,1862,1799)"

I want to know is it possible to get all maximum values for given array with single query (without using for or foreach and run query for every value of array). Thanks !

  • 写回答

2条回答 默认 最新

  • dowdw44426 2014-03-08 20:00
    关注

    You need to use GROUP BY using aggregate function you should group them ,for the first query there is where clause for one user so it will give your the max thread id but in second query you have 3 user ids so you need to group them to get 3 max thread ids per user

    SELECT MAX(thread_id) 
    FROM recipients 
    WHERE user_id IN (1215,1862,1799)
     GROUP BY user_id 
    

    fiddle demo

    GROUP BY (Aggregate) Functions

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源