MySQL在连接上仅选择1条记录,不包括匹配项

时间:2013-05-30 23:07:49

标签: mysql join

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

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个用户?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

更改您的GROUP BY - 您希望按growers.id而不是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

答案 1 :(得分: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应该对子查询有很大的帮助!)