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
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)
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With