LeSpotted44
LeSpotted44

Reputation: 67

Select last record mysql on left join

I have a table that stores all users connections ( date & ip ) and i want to retrieve with a single query all the users data (nickname , avatar ...) + the last record of my connections history table of this user ...

SELECT 
    *
FROM
    `users`
        LEFT JOIN
    `connections_history` ON `users`.`id` = `connections_history`.`guid`

How i can proceed thx

Upvotes: 0

Views: 3526

Answers (4)

Gordon Linoff
Gordon Linoff

Reputation: 1269823

You can do this with a correlated subquery in the ON clause:

SELECT u.*, ch.*
FROM `users` u LEFT JOIN
     `connections_history` ch
      ON ch.`guid` = u.`id` AND
         ch.date = (SELECT MAX(ch2.date)
                    FROM connections_history ch2
                    WHERE ch.guid = ch2.guid
                   );

This formulation allows the query to take advantage of an index on connections_history(guid, date).

Upvotes: 1

Paul Spiegel
Paul Spiegel

Reputation: 31792

Assuming that connections_history table has an AUTO_INCREMENT column id:

SELECT *
FROM (
    SELECT u.*, MAX(h.id) as hid
    FROM users u
    LEFT JOIN connections_history h ON u.id = h.guid
    GROUP BY u.id
) u
LEFT JOIN connections_history h ON h.id = u.hid

Upvotes: 2

Gurwinder Singh
Gurwinder Singh

Reputation: 39477

One way is finding the rows with max date for each guid in subquery and then join with users table.

Like this:

select *
from `users` u
left join (
    select *
    from `connections_history` c
    where date = (
        select max(date)
        from `connections_history` c2
        where c.`guid` = c2.`guid`
    )
) t on u.`id` = t.`guid`;

Upvotes: 0

Pரதீப்
Pரதீப்

Reputation: 93714

Unfortunately Mysql does not support window functions, you need Correlated sub-query to do this.

Try something like this

SELECT *
FROM   users
       LEFT JOIN connections_history ch
              ON users.id = ch.guid
                 AND EXISTS (SELECT 1
                             FROM   connections_history ch1
                             WHERE  ch.guid = ch1.guid
                             HAVING Max(ch1.date) = ch.date) 

Upvotes: 0

Related Questions