通过先查找最大行来连接两个表

时间:2014-12-08 21:25:20

标签: mysql

我想仅获取表m的最大行数据,并将其连接到表l以查找进度

表(M)

   id  labref  activity
    ---------------------
    1    x       ab
    2    x       cd
    3    x       ef
    4    y       jk
    5    y       il

表(l);

    id  activity  progress
    ---------------------
    1    ab       0
    2    cd       10
    3    ef       20
    4    jk       30
    5    il       40

当我跑去获得最大行时,它会起作用

select t1.* from m t1
left join m t2 on t1.labref = t2.labref
and t1.id < t2.id
where t2.id is null

但是当我运行以下查询来添加进度

select t1.id, t1.labref, t1.activity, sp.progress from m t1,  l sp
left join m t2 on t1.labref = t2.labref
and sp.location = t1.activity
and t1.id < t2.id
where t2.id is null

The error is:  Unknown column 'sp.progress' in 'field list'

我要找的结果是

id   labref   activity   progress
----------------------------------
3      x          ef       20
5      y          il       40

任何建议人员,先谢谢。

1 个答案:

答案 0 :(得分:2)

SELECT m.id, m.labref, m.activity, l.progress
    FROM (SELECT labref, MAX(id) as MaxId
              FROM m
              GROUP BY labref) q
        INNER JOIN m 
            ON q.MaxId = m.id
        INNER JOIN l
            ON m.activity = l.activity;