2014-05-13 56 views
1

我有我的DB這2個表:SQL:創建從2個表打印空值視圖時沒有記錄

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`; 
+0

我覺得你的問題是,AVG不能返回NULL。 – durbnpoisn

回答

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)

+0

感謝您的快速響應,我已經嘗試過,它的功能就像一個魅力!在七分鐘內我會接受答案:) – unmultimedio

+0

@ khale912 - 無後顧之憂,很高興我能幫上忙! – sgeddes