2016-06-28 9 views
1

私はBook(Bookid、Title)And Movie(Movieid、タイトル)とcheckout(memberid、bookid、movieid)の3つのテーブルを持っています。関連のない2つのテーブルを結合する

Movie: 

id   title 
---------- ------------- 
1   Life of Brian 
2   Airplane 
3   Rush 
4   Day of the De 
5   Star Wars 
6   Thin Red Line 
7   Crouching Tig 
8   Lawrence of A 
9   Office Space 

Book: 

id   title 
---------- ---------- 
1   Life of Pi 
2   Fellowship 
3   Two Towers 
4   Dune 
5   The Hobbit 
6   1984 
7   Tom Sawyer 
8   Catcher in 
9   To Kill a 
10   Domain Dri 

Checkout: 

member_id book_id  movie_id 
---------- ---------- ---------- 
6   1 
1   3 
2   4 
1   5 
1      1 
7      2 
6      3 
8      4 
6      5 

チェックアウトされていない書籍や映画をすべて選択します。

現在、私はこれらのクエリを使用しています。

create table MoviesNotCheckedOut (MovieID integer, MovieName text); 

    Insert Into MoviesNotCheckedOut 
    select m.id, m.title from movie m where 
    m.id NOT IN 
    (select c.member_id from checkout_item c); 

    create table BooksNotCheckedOut (BookID integer, BookName text); 

    Insert Into BooksNotCheckedOut 
    select b.id, b.title from book b where 
    b.id NOT IN 
    (select c.member_id from checkout_item c); 

create table BooksAndMoviesNotCheckedOut(BookID integer, BookName text, MovieID integer, MovieName text); 

insert into BooksAndMoviesNotCheckedOut 
select b.BookID,b.BookName,m.MovieID,m.MovieName from BooksNotCheckedOut b, MoviesNotCheckedOut m; 

しかし、私はこのような重複を取得しています表示するに

BookID  BookName MovieID  MovieName 
---------- ---------- ---------- ---------- 
3   Two Towers 3   Rush 
3   Two Towers 4   Day of the 
3   Two Towers 5   Star Wars 
3   Two Towers 9   Office Spa 
4   Dune  3   Rush 
4   Dune  4   Day of the 
4   Dune  5   Star Wars 
4   Dune  9   Office Spa 
5   The Hobbit 3   Rush 
5   The Hobbit 4   Day of the 
5   The Hobbit 5   Star Wars 
5   The Hobbit 9   Office Spa 
9   To Kill a 3   Rush 
9   To Kill a 4   Day of the 
9   To Kill a 5   Star Wars 
9   To Kill a 9   Office Spa 
10   Domain Dri 3   Rush 
10   Domain Dri 4   Day of the 
10   Domain Dri 5   Star Wars 
10   Domain Dri 9   Office Spa 

私は重複を削除するにはどうすればよいです。私はこのようなものとして、それを表示したい:

BookID  BookName  MovieID  MovieName 
_ _ _  _ _ _ _  _ _ _ _  _ _ _ _ _ _ 

1   xxxx   4   yyyy 
+0

結合の仕組みを学ぶには、しばらく時間を費やす必要があります。 –

+0

私は2つのテーブルを結合する関係が必要ですか?書籍と映画の間には関係がありません。 – leoOrion

+0

"BooksNotCheckedOut bから、MoviesNotCheckedOut m"は参加です。 –

答えて

2

あなたはunion allを使用することができます。ただし、これを2つの列として行う必要があります。

select 'movie' as which, m.id, m.title 
from movie m 
where not exists (select 1 from checkout co where co.movieid = m.id) 
union all 
select 'book' as which, b.id, b.title 
from book b 
where not exists (select 1 from checkout co where co.bookid = b.id); 
+0

「選択1」とは何ですか? – leoOrion

+2

@leoOrion行の有無をチェックするときに、列を選択するか、 '*'か単に '1'を選択するかは関係ありません。通常、 '1'はあなたが気にしないことを示すために、行の存在が既にいくつかのインデックスエントリから暗示されている場合、実際のテーブルにアクセスすることを避けるための最適化として使用されます。 –

+0

1は "任意の数の列を意味することができますが、気にしません" – leoOrion

関連する問題