简体   繁体   English

选择左连接上的最后一条记录mysql

[英]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 ... 我有一个表来存储所有用户的连接(date和ip),我想用一个查询来检索所有用户的数据(昵称,头像...)+该用户的连接历史记录表的最后一条记录...

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

How i can proceed thx 我如何进行

Assuming that connections_history table has an AUTO_INCREMENT column id : 假设connections_history表具有一个AUTO_INCREMENT列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

Unfortunately Mysql does not support window functions, you need Correlated sub-query to do this. 不幸的是, Mysql不支持window函数,您需要Correlated sub-query来执行此操作。

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) 

You can do this with a correlated subquery in the ON clause: 您可以在ON子句中使用相关子查询来执行此操作:

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) . 此公式使查询可以利用connections_history(guid, date)上的索引。

One way is finding the rows with max date for each guid in subquery and then join with users table. 一种方法是为子查询中的每个GUID查找具有最大日期的行,然后与users表联接。

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`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM