Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get last record of one to many relation

Tags:

mysql

I have two tables

users : id,name

health : id,status,test_date,user_id

health table containing user health history

now i want to get the last health test and user info of a specific user

I tried this query

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 

but i failed

like image 292
BaDr Amer Avatar asked Dec 09 '22 03:12

BaDr Amer


2 Answers

Try this:

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)
like image 150
Rahul Tripathi Avatar answered Dec 10 '22 15:12

Rahul Tripathi


This is an other option:

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

NOTE: "D" will result in a DERIVED table and therefore in a faster execution in MySQL 5.7+ or MariaDB 10+.

Reference:

  • Optimizing Derived Tables and View References
  • MySQL 5.7: Improved Performance of Queries with Derived Tables
like image 39
Marcos Avatar answered Dec 10 '22 15:12

Marcos