所有用户的每用户最新贷款

时间:2011-10-07 21:18:41

标签: php mysql pdo greatest-n-per-group

//编辑:

一切正常:

SELECT u.*,
    l.cod AS loans_cod,
    l.step AS loans_step
FROM users AS u
LEFT JOIN loans AS l
ON u.id = l.users_id
WHERE l.step < 12
    OR NOT EXISTS
        (SELECT l.id
            FROM loans
            WHERE l.users_id = u.id
        )
GROUP BY u.id

现在,我可以选择所有用户,以及他的最后一笔贷款。谢谢,我认为我的解决方案将帮助未来的用户。

3 个答案:

答案 0 :(得分:1)

如果你想要最后一笔贷款,你可以追加这样的东西

ORDER BY l.date DESC GROUP BY u.id

答案 1 :(得分:1)

SELECT u.*,
       l.cod  AS loans_cod,
       l.step AS loans_step
FROM   users AS u
       LEFT JOIN loans AS l
         ON u.id = l.users_id
WHERE  u.id != :id  
  AND  l.timestamp = (SELECT MAX(l.timestamp)
                      FROM loans AS l2
                      WHERE l2.users_id = l.users_id)

其中timestamp是表格中的一列,用于指示贷款何时创建或以其他方式为您提供可与之比较的时间。

答案 2 :(得分:0)

试试这个:

SELECT u.*, l.cod AS loans_cod, 
l.step AS loans_step 
FROM users AS u inner join
(
   select max(l.loan_id) as loan_id, l.users_id , l.cod, l.step
   from loans l 
   group by 
   l.users_id,l.cod,l.step
) as l
ON u.id = l.users_id  
WHERE u.id != :id 

注意:避免执行select *这是一种非常糟糕的做法。列出您只需要的所有列。