mysql 查询获取不同的最新记录

mysql query for getting distinct and lastest record

我做了如下视图(连接四个表):

ID  |  BookID  |    date    |  points  |
 1  |    11    | 2014-11-01 |    15    |
 1  |    11    | 2015-01-01 |    16    |
 1  |    11    | 2014-12-01 |    17    |
 1  |    12    | 2014-02-11 |    18    |
 1  |    12    | 2014-03-11 |    19    |
 1  |    12    | 2014-04-11 |    15    |
 1  |    13    | 2014-12-23 |    121   |
 1  |    14    | 2014-01-15 |    113   |
 1  |    14    | 2014-02-08 |    112   |

我想要这个视图的结果如下

ID  |  BookID  |    Date     |  points  |
 1  |    11    |  2015-01-01 |    16    |
 1  |    12    |  2014-04-11 |    15    |
 1  |    13    |  2014-12-23 |    121   |
 1  |    14    |  2014-02-08 |    112   |

它应该类似于具有最大日期并显示为单独点的独特图书 ID。 到目前为止,我已经尝试过按加入分组和按日期分组。但它有点结束了,因为我无法找到解决这个问题的方法。

我的查询是:

SELECT m1.* FROM viewPoints m1 LEFT JOIN viewPoints m2 
ON (m1.BookID = m2.BookID AND m1.Date < m2.Date)
WHERE m1.ID= 1 and m2.Date IS NULL

ORDER BY m1.BookID

任何帮助!提前致谢。

CREATE VIEW [BOOKLIST] AS
SELECT m1.* FROM viewPoints m1 LEFT JOIN viewPoints m2 
ON (m1.BookID = m2.BookID AND m1.Date < m2.Date)
WHERE m1.ID= 1 and m2.Date IS NULL
ORDER BY m1.BookID    

SELECT ID, DISTINCT BookID, Date, points FROM BOOKLIST
WHERE Date BETWEEN "start date" AND "end date"
SELECT * 
 FROM tablename
  WHERE DATE
 IN (

   SELECT MAX( DATE ) 
   FROM tablename
   GROUP BY bookid
   ORDER BY DATE DESC
  )
 ORDER BY DATE DESC 

也许这就是你想要的?

select v.* 
from viewPoints v
join (
    select 
       BookID, 
       max(date) max_date 
    from viewPoints
    where points is not null 
    group by BookID
) v2 on v.BookID = v2.BookID and v.date = v2.max_date
where v.points is not null
order by v.BookID

Sample SQL Fiddle

示例输出:

| ID | BOOKID |                            DATE | POINTS |
|----|--------|---------------------------------|--------|
|  1 |     11 |  January, 01 2015 00:00:00+0000 |     16 |
|  1 |     12 |    April, 11 2014 00:00:00+0000 |     15 |
|  1 |     13 | December, 23 2014 00:00:00+0000 |    121 |
|  1 |     14 | February, 08 2014 00:00:00+0000 |    112 |