如何从一个表中获取所有的行,但筛选第二个表?

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

我运行一个PHP页面会拉从一个表中的所有记录,内蒙古与其他两个表JOIN,然后列出所有结果的查询。但是在第二个表我只想要最新的记录。

这里是我的查询

SELECT * FROM wn_trailer 
INNER JOIN (
    SELECT id, trailer_id, trailer_status, trailer_assigned, MAX(last_update), trailer_lat, trailer_long
    FROM wn_trailer_history
) AS th ON wn_trailer.id = th.trailer_id 
INNER JOIN wn_trailer_status ON wn_trailer_status.id = th.trailer_status 
INNER JOIN wn_users ON wn_users.id = th.trailer_assigned 
ORDER BY trailer_number ASC

查询运行,但只返回第一条记录。

mysql sql
1个回答
3
投票

你想要一个额外JOIN带来数据上的最后更新日期。另外,你的子查询需要一个GROUP BY

SELECT *
FROM wn_trailer t INNER JOIN
     (SELECT trailer_id, MAX(last_update) as max_last_update
      FROM wn_trailer_history
      GROUP BY trailer_id
     ) tht
     ON t.id = tht.trailer_id INNER JOIN
     wn_trailer_history th
     ON th.trailer_id = tht.trailer_id AND
        th.last_update = tht.max_last_update INNER JOIN
     wn_trailer_status ts
     ON ts.id = th.trailer_status INNER JOIN
     wn_users u
     ON u.id = th.trailer_assigned 
ORDER BY trailer_number ASC;

我还添加表别名,以便查询更容易编写和阅读。

© www.soinside.com 2019 - 2024. All rights reserved.