获得一对多关系的最后记录

时间:2015-05-01 11:33:51

标签: mysql

我有两张桌子

  

用户:id,name

     

health:id,status,test_date,user_id

包含用户健康历史记录的健康状况表

现在我想获得特定用户的最后一次健康测试和用户信息

我试过了这个查询

SELECT users.*, health.* FROM users INNER JOIN health ON users.id=health.user_id
having (max(health.id)) order by users.id desc limit 50 

但我失败了

2 个答案:

答案 0 :(得分:9)

试试这个:

SELECT users.*, health.* FROM users  
INNER JOIN health  
    ON health.id = (SELECT id FROM health WHERE health.id = users.id ORDER BY id DESC LIMIT 1)

答案 1 :(得分:1)

这是另一个选择:

SELECT U.*, H.* 
FROM users AS U
  INNER JOIN (
    SELECT user_id, MAX(id) AS id
    FROM health
    GROUP BY user_id
  ) AS D
    ON D.user_id = U.user_id
  INNER JOIN health AS H
    ON H.id = D.id

注意“ D” 将导致DERIVED表,因此在MySQL 5.7+或MariaDB 10+中执行速度更快。

参考: