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

时间:2017-02-04 16:24:33

标签: mysql sql

我有一个存储所有用户连接的表(日期和IP),我想用单个查询检索所有用户数据(昵称,头像...)+我的连接历史记录表的最后一条记录用户......

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

我如何进行thx

4 个答案:

答案 0 :(得分:1)

假设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

答案 1 :(得分:0)

不幸的是Mysql不支持window个功能,您需要Correlated sub-query才能执行此操作。

尝试这样的事情

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) 

答案 2 :(得分:0)

您可以使用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
                   );

此公式允许查询利用connections_history(guid, date)上的索引。

答案 3 :(得分:0)

一种方法是在子查询中找到每个guid的最大日期行,然后与users表连接。

像这样:

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