mysql max date生成错误输出

ryevplcw  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(356)

我有以下表格。

letter table

letter_no   date    r_from  branch
1   2018-08-10  A   Admin
2   2018-08-10  B   Enginnering
3   2018-08-11  C   IT
4   2018-08-12  D   Admin

action table

action_id   letter  action_date status
1   1   2018-08-15  on-going
2   2   2018-08-12  on-going
3   1   2018-08-17  finished

desired output

letter_id   action_date status
1   2018-08-17  finished
2   2018-08-12  on-going

我使用下面的sql查询来获取输出

SELECT letter.letter_id, MAX(action.action_date), action.status FROM action
    LEFT JOIN action ON action.letter_id=letter.letter_id
    GROUP BY action.letter_id

但是查询将生成以下输出。

letter_id   action_date status
1   2018-08-15  on-going
2   2018-08-12  on-going

我不明白我做错了什么。有人能帮忙吗?

p1iqtdky

p1iqtdky1#

可以在相关子查询中使用聚合函数,如下所示:

select  * from action t1
   where t1.action_date in     
    (          
     select max(action_date) from action t2  
      where t2.letter=t1.letter
       )

http://sqlfiddle.com/#!9/02c4c/5号

id  letter  action_date     status
2   2      2018-08-12       on-going
3   1      2018-08-17       finished
knpiaxh1

knpiaxh12#

对于您的查询,有两个名为 action 而且没有别名,你也只是比较一下 letter_idJOIN ,您还需要进行比较 action_date 您可以使用下面的sql来实现它

SELECT a1.id,a1.letter_id,a1.action_date 
    FROM action a1
  JOIN
    (SELECT a.letter_id,max(a.action_date) as mdate 
         FROM action a GROUP BY a.letter_id) a2 
  ON a1.letter_id=a2.letter_id AND a1.action_date=a2.mdate

相关问题