[英]Efficient criteria query to only select the first and last result of a query?
[英]mysql select last result in IN query
我是mysql的初學者,我有兩個表。 日志表包含(電子郵件,日期時間,值),另一個是tmp,其中存在電子郵件。
我查詢
select distinct email, datetime
from Log
where email in (select email from tmp)
group by email;
結果是:
| email | datetime |
+----------------------------+---------------------+
| aaa@gmail.com | 2014-02-06 14:08:28 |
| bbb@gmail.com | 2014-05-22 18:53:39 |
| cc@gmail.com | 2014-05-22 18:51:19 |
+----------------------------+---------------------+
但是我需要的datetime應該是最新的,此查詢選擇第一個日期(較舊)。 我應該更改什么以獲得最新日期?
由於使用分組的事實,如果需要更新的分組,可以使用max()之類的聚合函數,否則可以使用min()
select email, max(datetime )
from Log
where email in (select email from tmp)
group by email;
並根據您的需要使用分組
嘗試這個
select distinct email, datetime
from Log
where email in (select email from tmp)
group by email
ORDER BY datetime desc
您可以使用max:
select distinct email, max(datetime)
from Log
where email in (select email from tmp)
group by email;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.