2013-06-11 152 views
1

我有一個視圖,下面有我想要顯示的所有內容,但只有在每個表格中的特定影片都添加了所有內容時纔會顯示(如果這樣做的話)。就像添加了電影一樣,只有當副本,演員,角色和流派已經連接到該特定電影時,視圖纔會顯示,但是如果沒有爲電影添加任何內容,它將不會顯示。我是這個新東西,所以任何幫助將不勝感激。顯示所有記錄,即使爲空

CREATE VIEW viewAllMovieDetails AS 
SELECT `tblMovie`.`MovieName`, `tblCopy`.`CpyEdition`, `tblCopy`.`CpyCondition`, 
     `tblCopy`.`CpyAmountPaid`, `tblCopy`.`CpyNote`, `tblMovie`.`MovieRating`, 
     `tblMovie`.`MovieLength`,`tblMovie`.`MovieYear`, `tblActor`.`ActLastName`, 
     `tblActor`.`ActFirstName`, `tblRole`.`Role`, `tblMovieGenre`.`GenGenre` 
FROM `tblCopy`, `tblMovie`, `tblActor`, `tblRole`, `tblMovieGenre`  
WHERE `tblCopy`.`MovieID` = `tblMovie`.`MovieID` AND `tblRole`.`MovieID` = `tblMovie`.`MovieID` 
    AND `tblRole`.`ActID` = `tblActor`.`ActID` AND `tblMovieGenre`.`MovieID` =     `tblMovie`.`MovieID`; 
+1

有一個看看這個:http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of -sql-joins.html – fancyPants

回答

2

您應該使用LEFT JOIN。如果它們是NULL,它們將以這種類型的連接顯示。

CREATE VIEW viewAllMovieDetails AS 
SELECT tblMovie.MovieName, tblCopy.CpyEdition, tblCopy.CpyCondition, 
     tblCopy.CpyAmountPaid, tblCopy.CpyNote, tblMovie.MovieRating, 
     tblMovie.MovieLength,tblMovie.MovieYear, tblActor.ActLastName, 
     tblActor.ActFirstName, tblRole.Role, tblMovieGenre.GenGenre 
FROM tblCopy 
LEFT JOIN tblMovie tm USING(MovieID) 
LEFT JOIN tblActor ta USING(ActID) 
LEFT JOIN tblRole tr ON tr.ActID = ta.ActID 
LEFT JOIN tblMovieGenre tg ON tg.MovieID = tm.MovieID; 

使用別名是很好的做法,以及;) 如果你把條件在你內心,而不是左聯接。

+0

它給了我這個錯誤:錯誤代碼:1054.'from子句'中的未知列'ActID'。 –

+0

沒關係,我弄明白了!非常感謝! –

+0

CREATE VIEW viewAllMovieDetails AS SELECT tblMovie.MovieName,tblCopy.CpyEdition,tblCopy.CpyCondition, tblCopy.CpyAmountPaid,tblCopy.CpyNote,tblMovie.MovieRating, tblMovie.MovieLength,tblMovie.MovieYear,tblActor.ActLastName, tblActor.ActFirstName, tblRole.Role,tblMovieGenre.GenGenre FROM tblMovie LEFT JOIN tblCopy ON tblCopy.MovieID = tblMovie.MovieID LEFT JOIN tblRole ON tblMovie.MovieID = tblRole.MovieID LEFT JOIN tblActor ON tblActor.ActID = tblRole.ActID LEFT JOIN tblMovieGenre ON tblMovieGenre.MovieID = tblMovie.MovieID; –

2

使用 「左連接」,而不是 「其中」

CREATE VIEW viewAllMovieDetails AS 
SELECT `tblMovie`.`MovieName`, `tblCopy`.`CpyEdition`, `tblCopy`.`CpyCondition`, 
     `tblCopy`.`CpyAmountPaid`, `tblCopy`.`CpyNote`, `tblMovie`.`MovieRating`, 
     `tblMovie`.`MovieLength`,`tblMovie`.`MovieYear`, `tblActor`.`ActLastName`, 
     `tblActor`.`ActFirstName`, `tblRole`.`Role`, `tblMovieGenre`.`GenGenre` 
FROM `tblMovie` left join tblCopy on tblMovie.mouvieId=tblCopy.mouvieId ...etc