MySQL:如何加入第一行

时间:2017-05-05 09:22:43

标签: mysql join

我有3个表, Master ,其他两个 TableA TableB Master 都有一个表与其他两个表有很多关系。

我想要的是让所有主记录只与TableA和TableB中的最新记录相关联,所以我使用左连接如下,

SELECT
   *
FROM
Master master
LEFT JOIN (SELECT ta.* FROM TableA ta WHERE ta.masterId = master.id LIMIT 1 ORDER BY ta.id DESC ) as tableA
LEFT JOIN (SELECT tb.* FROM TableB tb WHERE tb.masterId = master.id LIMIT 1 ORDER BY tb.id DESC ) as tableB
WHERE master.status = 1

但是上面的sql语句遇到错误,

Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ta' from one of the SELECTs cannot be used in global ORDER clause
; bad SQL grammar ... Table 'ta' from one of the SELECTs cannot be used in global ORDER clause

它抱怨.. in global ORDER clause,但似乎不是这样,所有订单子句都在子查询中使用?

我的sql出了什么问题,它可能很幼稚,但有没有更好的方法来实现我的要求?

感谢。

2 个答案:

答案 0 :(得分:1)

LIMIT 1ORDER BY子句应该切换位置

答案 1 :(得分:1)

您应首先获取tablea的最后一条记录,每个masterId的tableb,然后left join tablea和tableb以获取所有记录:

select m.*, ta.*, tb.*
from master m
left join (
    select tablea.*
    from tablea
    join (select max(id) as id from tablea group by masterId) tmp
    on tablea.id = tmp.id
) ta on ta.masterId = m.id
left join (
    select tableb.*
    from tableb
    join (select max(id) as id from tableb group by masterId) tmp
    on tableb.id = tmp.id
) tb on tb.masterId = m.id