只是为了扩展 Oskon 的答案;脚本可能如下所示:(我在这里使用了临时表 - 只需删除 # 以使其永久化)
----create the tables
CREATE TABLE #tblMovie
(
MovieID int NOT NULL
,MovieName varchar(100) NULL
,MovieDirectorID int NULL
----add more fields here if you want
)
CREATE TABLE #tblGenre
(
GenreID int NOT NULL
,GenreName varchar(100) NULL
)
CREATE TABLE #tblMovieGenre ----this is where the genres of the movies are listed
(
MovieGenreID int NOT NULL --id for this table (just for indexing)
,MovieID int NOT NULL --movie id from #tblmovie
,GenreID int NOT NULL --genre id from #tblGenre
)
----insert the information
INSERT INTO #tblMovie (MovieID,MovieName,MovieDirectorID)
VALUES (1,'Movie 1 Name',3)
,(2,'Movie 2 Name',10)
,(3,'Movie 3 Name',2)
INSERT INTO #tblGenre (GenreID, GenreName)
VALUES (1,'Comedy')
,(2,'Horror')
,(3,'Action')
,(4,'Thriller')
----add more genres
INSERT INTO #tblMovieGenre (MovieGenreID,MovieID,GenreID)
VALUES (1,1,1) --movie 1 is a comedy
,(2,2,3) --movie 2 is an action movie
,(3,3,3),(3,3,4) --movie 3 is an action/thriller movie
----Now find the genres for a movie (run this bit as many times as you want)
SELECT
T3.GenreName
FROM
#tblMovie T1
INNER JOIN #tblMovieGenre T2
ON T1.MovieID = T2.MovieID
LEFT OUTER JOIN #tblGenre T3
ON T2.GenreID = T3.GenreID
WHERE
T1.MovieName = 'Movie 3 Name' --put your movie name here