2010-11-08 71 views
2

如何創建一個可以獲取每種類型的最新條目的Mysql查詢。然後對它們進行計數並根據名稱顯示。謝謝Mysql用扭曲查詢最近的條目

MySQL數據庫

Id | Date  | Type | Name | Time 
1 11/8/2010 | 12312| Bill | 7:30 AM 
2 11/8/2010 | 12311| Bill | 7:45 PM 
3 11/8/2010 | 12312| Bill | 8:30 AM 
4 11/8/2010 | 12310| Bill | 9:40 AM 
5 11/8/2010 | 12312| Rich | 7:30 AM 
6 11/8/2010 | 12312| Rich | 7:45 PM 
7 11/8/2010 | 12312| Jim | 8:30 AM 
8 11/8/2010 | 12310| Jim | 9:40 AM 
9 11/8/2010 | 12312| Jim | 7:30 AM 
10 11/8/2010 | 12310| Jim | 7:45 AM 

MySQL查詢/ PHP的輸出

Bill = 3  
2 11/8/2010 | 12311| Bill | 7:45 PM 
3 11/8/2010 | 12312| Bill | 8:30 AM 
4 11/8/2010 | 12310| Bill | 9:40 AM 
Rich = 1 
6 11/8/2010 | 12312| Rich | 7:45 PM 
Jim = 2 
7 11/8/2010 | 12312| Jim | 8:30 AM 
8 11/8/2010 | 12310| Jim | 9:40 AM 

回答

1
SELECT m.* 
FROM (
     SELECT DISTINCT name, type 
     FROM mytable 
     ) md 
JOIN mytable m 
ON  m.id = 
     (
     SELECT id 
     FROM mytable mi 
     WHERE mi.name = md.name 
       AND mi.type = md.type 
     ORDER BY 
       mi.name DESC, mi.type DESC, mi.date DESC, mi.id DESC 
     LIMIT 1 
     ) 

創建於mytable (name, type, date, id)這個索引快速地工作。