Select Join with last Mysql record

Asked

Viewed 18 times

0

Good morning,

I’m having trouble doing this search in mysql:

I would like to get all active users with their last trips (last registration):

inserir a descrição da imagem aqui

Command used:

SELECT u.id, t.user_id, u.name, u.status, t.name as last_trip
FROM users u
LEFT JOIN trips t ON u.id = t.user_id AND t.id = ( SELECT MAX(*) FROM trips)
WHERE u.status = 'active';

1 answer

0


     SELECT u.id AS `user_id`, u.`name`, u.`status`,
       (SELECT t.`name` FROM trips t WHERE t.user_id = u.id ORDER BY t.id DESC LIMIT 1) AS `last_trip`
     FROM users u
     WHERE u.`status` = "active"

This is probably not the perfect solution, but it already solves your problem.

  • And if I want to bring all the fields of the 2 tables, the Trips table being the last record?

  • 1

    SELECT u.*, t.*
FROM users u
LEFT JOIN trips t ON t.user_id = u.id
WHERE t.id = (SELECT MAX(tr.id) FROM trips tr WHERE tr.user_id = u.id AND u.status = "active")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.