SQL:从没有记录时打印空值的2个表创建视图

时间:2014-05-13 17:51:54

标签: sql average sql-view

我在我的数据库中有这两个表:

LESSONS                RATINGS
ID | NAME              ID | LESSON | RATING
1    lesson1           1    1        4
2    lesson2           2    2        2
3    lesson3           3    1        5
4    lesson4           4    4        2
5    lesson5           5    3        1
6    lesson6           6    2        5
7    lesson7           7    6        3

我想要一个向我展示这样的视图:

LESSONS_RATINGS
IDL| NAME     | RATING        
1    lesson1    4.5
2    lesson2    3.5
3    lesson3    1
4    lesson4    2
5    lesson5    NULL
6    lesson6    3
7    lesson7    NULL

但到目前为止我能够得到的是:

LESSONS_RATINGS
IDL| NAME     | RATING        
1    lesson1    4.5
2    lesson2    3.5
3    lesson3    1
4    lesson4    2
6    lesson6    3

请注意,缺少NULL记录。这就是为什么在表格里面没有第5和第7课的记录。我这样做:

CREATE OR REPLACE VIEW `LESSONS_RATINGS` AS
select 
    `l`.`ID` AS `IDL`,
    `l`.`NAME` AS `NAME`,
    CASE WHEN AVG(`lr`.`RATING`) IS NULL THEN NULL ELSE AVG(`lr`.`RATING`) END AS `RATING`
from
    `LESSONS` AS `l`,
    `RATINGS` AS `lr`
where
    (`l`.`ID` = `lr`.`ID`)
group by `l`.`ID`;

1 个答案:

答案 0 :(得分:1)

使用OUTER JOIN

select 
    `l`.`ID` AS `IDL`,
    `l`.`NAME` AS `NAME`,
    AVG(`lr`.`RATING`) AS `RATING`
from
    `LESSONS` AS `l` LEFT JOIN `RATINGS` AS `lr`
        ON `l`.`ID` = `lr`.`ID`
group by `l`.`ID`;

此外,我不认为需要Case声明 - 您只需使用AVG(lr.rating)