我想从3个不同的表创建一个视图,而不是重复输出。我目前的代码似乎正确地组织了主题书籍。但是,它会将每个书名打印到同一个作者,一旦完成,它将移动到下一个作者。而不是15行,它最终是270。
CREATE VIEW book_summary(author_first_name, author_last_name, book_title, subject)
AS SELECT DISTINCT first_name, last_name,title, subject
FROM authors, books left join subjects
ON subjects.subject_id = books.subject_id;
我试过通过SOF找到答案。我从Thread遇到了DISTINCT和LEFT JOIN。我只是觉得我没有正确使用它
Output:
Andrew | Brookins | 2001: A Space Odyssey | Science Fiction
Andrew | Brookins | Bartholomew and the Oobleck | Children's Books
Andrew | Brookins | Dune | Science Fiction
Andrew | Brookins | Dynamic Anatomy | Arts
Andrew | Brookins | Franklin in the Dark | Children's Books
Andrew | Brookins | Goodnight Moon | Children's Books
Andrew | Brookins | Learning Python | Computers
Andrew | Brookins | Little Women | Drama
Andrew | Brookins | Perl Cookbook | Computers
Andrew | Brookins | Practical PostgreSQL | Computers
Andrew | Brookins | Programming Python | Computers
Andrew | Brookins | The Cat in the Hat | Children's Books
Andrew | Brookins | The Shining | Horror
Andrew | Brookins | The Tell-Tale Heart | Horror
Andrew | Brookins | The Velveteen Rabbit | Classics
(对于我在另一张桌子上的每位作者继续这种趋势)。
答案 0 :(得分:1)
使用CROSS JOIN/comma syntax
时会发生这种情况:
CREATE VIEW book_summary
(author_first_name, author_last_name, book_title, subject)
AS
SELECT DISTINCT first_name, last_name,title, subject
FROM authors, books --here is the problem
left join subjects
ON subjects.subject_id = books.subject_id;
应该是:
CREATE VIEW book_summary
(author_first_name, author_last_name, book_title, subject)
AS
SELECT first_name, last_name,title, subject
FROM authors a
JOIN books b
ON a.col_name = b.col_name
left join subjects s
ON s.subject_id = b.subject_id;