MySQL LEFT JOIN只有1行,具体取决于MAX()值

问题描述 投票:0回答:2

表格1

ID | Name
1    Brain
2    Amy

表2:

ID | WorkDay    | MissionCode
1    2019-01-01    2360
1    2019-02-01    2470
2    2019-01-01    4470
2    2019-02-01    7210

我想要实现的是,我想得到所有表1字段并在表2上保持连接但只有最新的WorkDay值,如下所示:

预期结果

ID | Name | WorkDay    | MissionCode
1    Brain  2019-02-01   2470
2    Amy    2019-02-01   7210

到目前为止我尝试过的是:

SELECT 
    table1.*, t2.WorkDay, t2.MissionCode
FROM 
    table1
LEFT JOIN
    (SELECT
        *
     FROM
        table2
     ORDER BY
        WorkDay DESC
     LIMIT 0,1) AS t2
ON
   t2.id = table1.id

但它从table2返回NULL值,如下所示:

ID | Name | WorkDay    | MissionCode
1    Brain  NULL         NULL
2    Amy    NULL         NULL

我测试了相同的查询,在内部联接的select命令中添加了额外的WHERE子句,并且它成功了。

SELECT 
    table1.*, t2.WorkDay, t2.MissionCode
FROM 
    table1
LEFT JOIN
    (SELECT
        *
     FROM
        table2
     **WHERE id = 1**
     ORDER BY
        WorkDay DESC
     LIMIT 0,1) AS t2
ON
   t2.id = table1.id

它返回ok,对于第一行:

ID | Name | WorkDay    | MissionCode
1    Brain  2019-02-01   2470
2    Amy    NULL         NULL

但我不能用

WHERE id = table1.id 

因为MySQL说

Unknown column 'table1.id' in 'where clause'

那么,这是正确的方法是什么?

mysql greatest-n-per-group
2个回答
3
投票

您可以使用简单的JOINtable2,只需将MAX(WorkDay)条件作为相关子查询放入JOIN条件,您可以在其中访问table1 id值:

SELECT *
FROM table1 t1
JOIN table2 t2 ON t2.id = t1.id AND
                  t2.WorkDay = (SELECT MAX(WorkDay) 
                                FROM table2 
                                WHERE table2.id = t1.id)

输出:

ID  Name    ID  WorkDay     MissionCode
1   Brain   1   2019-02-01  2470
2   Amy     2   2019-02-01  7210

Demo on dbfiddle


0
投票

这也输出相同但注意@ Nick的答案更好 ---------- ------------ 1

select
  t1.id,t1.name,t2.workday,t2.Missioncode
  from t1
  left join t2 on 
  t1.id=t2.id
  and t2.workday =(select max(workday) from t2 );

----------2------------

 select t1.id,t1.name,
  (select max(workday) from t2 where t2.id=t1.id)as workday,
  (select max(MissionCode) from t2 where t2.id=t1.id)as missioncode
  from t1;
热门问题
推荐问题
最新问题