创建总和的视图,选择min并选择子表的最大值

时间:2017-02-08 23:24:11

标签: mysql

我有3个表,我想加入一个视图

委员会表:

idCommission: int
name:         varchar
...

季节:

idSeason:     int
since:        date
till:         date

Seasons_in_commission:

idCommission: int
idSeason:     int

结果视图:

idCommission: int    | ID for referencing
Commission.*         | All other from Commission table
since:        date   | Min of all its (from) seasons
till:         date   | Max of all its (till) seasons
seasons:      int    | Count of its seasons

我试过,但我发现,我需要在子查询中逐行引用,我不知道该怎么做。

SELECT Commission.*, 
MIN(
  SELECT since FROM Seasons_in_commission 
  JOIN Season USING(idSeason) 
  WHERE idCommission = currentRow.idCommission /*<- this part is wrong */
) as Since, MAX(...) as Till, COUNT(...) as Seasons FROM Commission

1 个答案:

答案 0 :(得分:1)

我认为你不需要任何子查询。试试这个:

SELECT Commission.*, MIN(since) AS Since, MAX(till) AS Till, COUNT(*) AS Seasons
  FROM Commission
  JOIN Seasons_in_commission USING (idCommission)
  JOIN Season USING (idSeason)
 GROUP BY idCommission;

(请注意,这只适用于ONLY_FULL_GROUP_BY已禁用。)