SQLite从2个连接中获取MAX

时间:2015-03-10 11:10:31

标签: sqlite join max

我想从2张桌子(品尝,评级)中得到一些分数加入第一张桌子(葡萄酒)。 1种葡萄酒可以拥有多种品尝和评级。

结构

table wines
-----------
id 
name

table tastings
-------------
id 
wine_id
date
score

table ratings
-------------
id
wine_id
date
score

场景:1种葡萄酒有2种不同日期和分数的品尝,3种不同日期和分数的评级。

我想通过最后品尝(最大日期)和分数以及最后评级(最大日期)和分数来获得葡萄酒。

示例数据:

Wines:
-----
id: 1
name: Beaulieu Vineyard

tastings:
--------
id: 1
wine_id: 1
date: 2014-01-01
score: 4
-
id: 2
wine_id: 1
date: 2015-02-02
score: 5

ratings:
--------
id: 1
wine_id: 1
date: 2013-04-04
score: 6
-
id: 2
wine_id: 1
date: 2014-05-05
score: 7
-
id: 3
wine_id: 1
date: 2015-06-06
score: 8

所以想要的结果是:

Beaulieu Vineyard | Tasting: 2015-02-02 - score: 5 | Rating: 2015-06-06 - score: 8

我当前的查询有效:

SELECT   
wines.winery,  
MAX(tastings.date) AS tasting_date,
MAX(ratings.date) AS rating_date
FROM wines    
LEFT JOIN tastings ON wines.id = tastings.wine_id AND tastings.status=1  
LEFT JOIN ratings ON wines.id = ratings.wine_id AND ratings.status=1  
WHERE wines.status = 1   
GROUP BY wines.id    
ORDER BY wines.winery

问题是当我尝试捕获与每个品尝和每个配对相关的正确分数时:

SELECT   
wines.winery,  
MAX(tastings.date) AS tasting_date, tastings.score,
MAX(ratings.date) AS rating_date, ratings.score
FROM wines    
LEFT JOIN tastings ON wines.id = tastings.wine_id AND tastings.status=1  
LEFT JOIN ratings ON wines.id = ratings.wine_id AND ratings.status=1  
WHERE wines.status = 1   
GROUP BY wines.id    
ORDER BY wines.winery

分数错误:结果未显示与MAX(日期)对应的正确分数。

1 个答案:

答案 0 :(得分:1)

SQLite可以从与MAX()匹配的行中获取值,但仅当存在单个MAX()时才有效。

您必须使用子查询来查找值:

SELECT winery,
       (SELECT MAX(date)
        FROM tastings
        WHERE wine_id = wines.id
          AND status = 1
       ) AS tasting_date,
       (SELECT score
        FROM tastings
        WHERE wine_id = wines.id
          AND status = 1
        ORDER BY date DESC
        LIMIT 1
       ) AS tasting_score,
       (SELECT MAX(date)
        FROM ratings
        WHERE wine_id = wines.id
          AND status = 1
       ) AS rating_date,
       (SELECT score
        FROM ratings
        WHERE wine_id = wines.id
          AND status = 1
        ORDER BY date DESC
        LIMIT 1
       ) AS rating_score,
FROM wines
WHERE status = 1
ORDER BY winery

或者,在进行分组之前查找最大日期:

SELECT wines.winery,
       tasting_date,
       tastings.score,
       rating_date,
       ratings.score
FROM wines
LEFT JOIN (SELECT wine_id AS id,
                  MAX(date) AS tasting_date,
                  score
           FROM tastings
           WHERE status = 1
           GROUP BY wine_id
          ) AS tastings USING (id)
LEFT JOIN (SELECT wine_id AS id,
                  MAX(date) AS rating_date,
                  score
           FROM ratings
           WHERE status = 1
           GROUP BY wine_id
          ) AS ratings USING (id)
WHERE wines.status = 1
ORDER BY wines.winery