在GROUP BY之前LEFT JOIN + ORDER BY

时间:2018-05-03 14:49:02

标签: mysql group-by left-join sql-order-by

我有两张桌子:公司和电子邮件。

我想选择每家公司的最后一封电子邮件

我试过了:

SELECT * 
  FROM companies 
  LEFT 
  JOIN emails 
    ON companies.company_id = emails.company_id 
 WHERE companies.status = 'active' 
 GROUP 
    BY emails.company_id 
 ORDER  
    BY emails.date DESC;

但是这不起作用,ORDER BY部分应该以某种方式在GROUP BY部分之前,因为我想获得每个公司的最后一封电子邮件,而不是对最终结果进行排序。

有人可以帮助我吗?

感谢。

更新

我最终这样做了:

SELECT * 
  FROM companies 
  LEFT 
  JOIN (
       SELECT company_id, date
         FROM emails 
        ORDER
           BY date DESC
       ) emails
     ON companies.company_id = emails.company_id 
  WHERE companies.status = 'active' 
  GROUP 
     BY emails.company_id;

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

如果我以正确的方式理解你的问题,我认为这样的事情可行。

SELECT * FROM companies c 
LEFT JOIN emails e ON c.company_id = e.company_id
AND (e.company_id, e.date) IN (
    SELECT company_id, max(date) FROM emails GROUP BY company_id
)
WHERE c.status = 'active';

编辑:用Thorsten回答更新