我有三个表,Book(Bookid,title)和Movie(Movieid,title)和checkout(memberid,bookid,movieid)。
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 :(得分:2)
您可以使用union all
;但是,您应该将其作为两列:
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);