1

我有一个查询,显示用户列表及其上次登录日期。它“如果”他们有登录历史记录,但如果他们没有登录历史记录,它不包括他们。即使他们没有登录历史记录,如何让所有用户显示?

SELECT SQL_CALC_FOUND_ROWS growers.*,ld2.ip,ld2.login_date as last_login 
FROM growers 
LEFT JOIN ( 
    SELECT * 
    FROM log_logins 
    WHERE user_type = "grower" 
    ORDER BY login_date DESC 
    ) 
as ld2 ON (ld2.user_id = growers.id)
GROUP BY user_id 
ORDER BY growers.id DESC

我虽然“左”连接会包括它们,即使连接不匹配任何东西但它不匹配。我不明白的另一件事是当我删除所有日志记录时,此查询总是返回 1 个用户?

谢谢您的帮助。

4

2 回答 2

1

更改您的GROUP BY- 您希望按growers.idnot进行分组,ld2.user_id因为 ld2.user_id 可能是NULL.

SELECT SQL_CALC_FOUND_ROWS growers.*,ld2.ip,ld2.login_date as last_login 
FROM growers 
   LEFT JOIN ( 
       SELECT * 
       FROM log_logins 
       WHERE user_type = "grower" 
       ORDER BY login_date DESC 
    ) 
   as ld2 ON (ld2.user_id = growers.id)
GROUP BY growers.id 
ORDER BY growers.id DESC
于 2013-05-30T23:15:02.560 回答
0

您使用 LEFT JOIN 的想法是正确的,但我认为您可以稍微简化子查询。

未经测试,但试试这个:

SELECT SQL_CALC_FOUND_ROWS growers.*,ld2.ip, ld2.login_date as last_login 
FROM growers 
LEFT JOIN log_logins ld2 ON (user_id = growers.id)
WHERE ld2.login_date = ( SELECT MAX(login_date) FROM log_logins WHERE user_id = ld2.user_id)
GROUP BY user_id 
ORDER BY growers.id DESC

(如果它非常慢,在 login_date 和 user_id 上索引 log_logins 应该对子查询有很大帮助!)

于 2013-05-30T23:14:28.517 回答