Reputation: 173
I have three tables(simplified)
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))
Data in movie
id title
---------------------------
1 | Inception
2 | The Dark Knight
Data in genre
id type
---------------------
1 | action
2 | adventure
3 | thriller
Data in movie_genre
movie_id genre_id
----------------------------
1 | 1
1 | 2
2 | 1
2 | 3
I want to display movie name with its genre types displayed in one column. So, the output would be
title | genres
-----------------------------------------
Inception | action adventure
The Dark Knight | action thriller
I tried to do it in this way
select
movie.title, genre.type
from
movie, genre
where
movie.id = movie_genre.movie_id
and genre.id = movie_genre.genre_id;
but it says :
The multi-part identifier "movie_genre.movie_id" could not be bound.
The multi-part identifier "movie_genre.genre_id" could not be bound.
I am very new to SQL, any help would be appreciated.
Edit :
Using
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
OR
select movie.title, genre.type
from movie, genre, movie_genre
where
movie.id = movie_genre.movie_id
and genre.id = movie_genre.genre_id;
The output is now,
title | genres
-----------------------------------------
Inception | action
Inception | adventure
The Dark Knight | action
The Dark Knight | thriller
How could I display genres in one row?
Upvotes: 1
Views: 1919
Reputation: 69524
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
Upvotes: 3
Reputation: 7
I believe you will need to add the 'movie_genre' to FROM, e.g:
SELECT movie.title, genre.type FROM (movie, genre, movie_genre) WHERE ....
Upvotes: -2