![](/img/trans.png)
[英]How to get data from two temporary tables and insert in third table without adding new row in 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.movie_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.