gpt4 book ai didi

sql - 合并两个不相关的表

转载 作者:行者123 更新时间:2023-12-03 18:45:38 25 4
gpt4 key购买 nike

我有三个表,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

我想选择所有尚未 checkout 的书籍和电影。

目前我正在使用这些查询。
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

最佳答案

您可以使用 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);

关于sql - 合并两个不相关的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38076854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com