从MySQL表中获取最大值行

时间:2018-10-02 05:57:26

标签: mysql sql

我在mysql callde“投诉”和“操作”中有2个表。我想对每个投诉采取最后的行动。表格是:

Complaint:
complaint_id    complaint_title
--------------------------------
1               Abc complanint
2               Xyz complaint
3               Dummy Complaint

Action:
ser_id    complaint_id    action_id    action_date
1         1               1            2018-09-05
2         1               2            2018-09-07
3         1               3            2018-09-10
4         2               1            2018-09-08
5         3               1            2018-09-15
6         3               2            2018-09-18

现在我想得到如下结果:

ser_id    complaint_id    action_id    action_date
3         1               3            2018-09-10
4         2               1            2018-09-08
6         3               2            2018-09-18

DB fiddle

3 个答案:

答案 0 :(得分:1)

使用join和'',对于以下查询所需的预期结果,

group by

或者您可以在

中使用
    select complaint_id, 
   max(ser_id),
   max(action_id),
   max(action_date) 
   from Action a join Complaint c on a.complaint_id=c.complaint_id
  group by complaint_id

https://www.db-fiddle.com/f/DcKnndn4ZhaiTsJJj5gBG/2

答案 1 :(得分:1)

此查询将为您提供所需的结果。它在Complaints上将Actions连接到complaint_id,在MAX(action_date)具有complaint_id的行上也是如此:

SELECT a.*
FROM Complaints c
JOIN Actions a ON a.complaint_id = c.complaint_id AND
    a.action_date = (SELECT MAX(action_date) 
                     FROM Actions a1 
                     WHERE a1.complaint_id = c.complaint_id)

输出:

ser_id  complaint_id    action_id   action_date
3       1               3           2018-09-10
4       2               1           2018-09-08
6       3               2           2018-09-18

SQLFiddle demo

答案 2 :(得分:1)

尝试一下:

select @rn := 1, @complaint_id_lag := 0;

select user_id, complaint_id, action_id, action_date from (
  select case when complaint_id = @complaint_id_lag then @rn := @rn + 1 else @rn := 1 end rn,
         @complaint_id_lag := complaint_id complaint_id,
         user_id, action_id, action_date
  from Action
  order by complaint_id, action_date desc
) a where rn = 1;

Demo