簡體   English   中英

如何使用第三個表SQL Server從兩個相關的表中檢索數據

[英]How to retrieve data from two tables related using a third table, SQL Server

我有三張桌子(簡體)

movie(id int primary key identity, title varchar(20) not null)
genre(id int primary key identity, type varchar(10) not null)

movie_genre(movie_id int references movie(id), 
            genre_id int references genre(id), 
            primary key(movie_id, genre_id))

電影中的數據

id          title
---------------------------
1     |     Inception
2     |     The Dark Knight

數據類型

id          type 
---------------------
1     |     action 
2     |     adventure 
3     |     thriller

movie_genre中的數據

movie_id          genre_id 
----------------------------
1               |     1 
1               |     2 
2               |     1 
2               |     3 

我想顯示電影名稱,並將其流派類型顯示在一欄中。 因此,輸出將是

title              |     genres 
-----------------------------------------
Inception          |     action adventure 
The Dark Knight    |     action thriller

我試圖用這種方式

select 
    movie.title, genre.type 
from 
    movie, genre 
where 
    movie.id = movie_genre.movie_id 
    and genre.id = movie_genre.genre_id;

但它說:

無法綁定多部分標識符“ movie_genre.movi​​e_id”。
不能綁定多部分標識符“ movie_genre.genre_id”。

我對SQL非常陌生,將不勝感激。

編輯:
運用

SELECT G.[Type] ,M.[Title]
FROM movie_genre MG  
LEFT JOIN genre G ON MG.genre_id = G.ID
LEFT JOIN movie M ON MG.Movie_ID = M.ID

要么

select movie.title, genre.type 
from movie, genre, movie_genre
where
movie.id = movie_genre.movie_id 
and genre.id = movie_genre.genre_id;

現在的輸出是

    title              |     genres 
-----------------------------------------
Inception          |     action
Inception          |     adventure 
The Dark Knight    |     action
The Dark Knight    |     thriller

如何在一行中顯示流派?

SELECT G.[Type] 
       ,M.[Title]
FROM movie_genre MG  
LEFT JOIN genre G ON MG.genre_id = G.ID
LEFT JOIN movie M ON MG.Movie_ID = M.ID

取得清單

SELECT DISTINCT M.[Title]
      ,STUFF((
           SELECT ' ' + G.[Type] 
           FROM genre G INNER JOIN movie_genre MG
           ON  MG.genre_id = G.ID
           WHERE MG.Movie_id = Mov.Movie_id
           FOR XML PATH(''),TYPE)
            .value('.','NVARCHAR(MAX)'),1,1, '') Genre
FROM movie_genre Mov  
INNER JOIN movie M ON Mov.Movie_ID = M.ID

要么

SELECT DISTINCT M.[Title]
      ,STUFF(List,1,1, '') Genre
FROM @movie_genre Mov  
INNER JOIN @movie M 
ON Mov.Movie_ID = M.ID
             CROSS APPLY 
                       (
                       SELECT ' ' + G.[Type] 
                       FROM @genre G INNER JOIN @movie_genre MG
                       ON  MG.genre_id = G.ID
                       WHERE MG.Movie_id = Mov.Movie_id
                       FOR XML PATH('')
                       )Gen(List)

SQL FIDDLE

我相信您需要在FROM中添加“ movie_genre”,例如:

SELECT movie.title, genre.type FROM (movie, genre, movie_genre) WHERE ....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM