2017-02-17 30 views
0

我試圖創建一些表,具有以下特點:如何輕鬆獲取所有密鑰的最新版本的數據?

  • 存儲數據的所有版本的特定鍵
  • 能夠很容易地獲得最新的數據版本的所有鍵

我的架構如下:

CREATE TABLE WebSitesStatus(
    -- Host name of the site in question. 
    Host String(40) NOT NULL, 
    -- When the information on the site was last updated. 
    UpdateDate Date NOT NULL, 

    HttpsWorks BOOL NOT NULL, 
    ModernTls BOOL NOT NULL, 

) PRIMARY KEY(Host, UpdateDate DESC); 

所以表的例子子集可能是:

+--------------+------------+------------+-----------+ 
| Host   | UpdateDate | HttpsWorks | ModernTls | 
+--------------+------------+------------+-----------+ 
| foobar.com | 2016-10-14 | true  | false  | 
| google.com | 2016-10-14 | true  | true  | 
| google.com | 2016-04-23 | false  | false  | 
| nytimes.com | 2016-10-14 | false  | false  | 
| nytimes.com | 2016-05-25 | true  | true  | 
| nytimes.com | 2016-04-25 | true  | false  | 
| nytimes.com | 2016-04-23 | true  | false  | 
| paypal.com | 2016-10-14 | true  | false  | 
+--------------+------------+------------+-----------+ 

我想找到一種方法來找回

+--------------+------------+------------+-----------+ 
| Host   | UpdateDate | HttpsWorks | ModernTls | 
+--------------+------------+------------+-----------+ 
| foobar.com | 2016-10-14 | true  | false  | 
| google.com | 2016-10-14 | true  | true  | 
| nytimes.com | 2016-10-14 | false  | false  | 
| paypal.com | 2016-10-14 | true  | false  | 
+--------------+------------+------------+-----------+ 

但結構並不讓我很容易地做到這一點。有沒有辦法輕鬆地做這個查詢?

回答

0

這個查詢:

SELECT t.Host, MAX(t.UpdateDate) AS UpdateDate 
FROM WebSitesStatus AS t 
GROUP BY t.Host 

只返回行的主鍵,你想:

+--------------+------------+ 
| Host   | UpdateDate | 
+--------------+------------+ 
| foobar.com | 2016-10-14 | 
| google.com | 2016-10-14 | 
| nytimes.com | 2016-10-14 | 
| paypal.com | 2016-10-14 | 
+--------------+------------+ 

爲了讓你必須JOIN這回同一個表,這樣其他列:

SELECT p.Host, p.UpdateDate, q.HttpsWorks, q.ModernTls, 
FROM (SELECT t.Host, MAX(t.UpdateDate) AS UpdateDate 
     FROM WebSitesStatus AS t 
     GROUP BY t.Host) AS p 
JOIN WebSitesStatus AS q 
ON p.Host = q.Host AND p.UpdateDate = q.UpdateDate; 

產生這些數據,這是你想要的:

+--------------+------------+------------+-----------+ 
| Host   | UpdateDate | HttpsWorks | ModernTls 
+--------------+------------+------------+-----------+ 
| amazon.co.uk | 2016-10-14 | true  | false  | 
| amazon.com | 2016-10-14 | true  | true  | 
| nytimes.com | 2016-10-14 | false  | false  | 
| paypal.com | 2016-10-14 | true  | false  | 
+--------------+------------+------------+-----------+ 

這有點低效,因爲它會掃描您的表兩次:一次獲取主鍵值,然後再次獲取所有其他值。但它可能是最乾淨的方法。

相關問題