查询作者和书籍的流派和子流派

时间:2015-05-27 22:35:07

标签: database oracle database-design

我想为图书创建一个数据库。数据库应包括下面显示的表格。 假设我想写一个回复authors.first_nameauthor.last_nameworks.title撰写ha句诗作者的查询;诗歌是流派,ha句是子流派。

我真的不知道如何编写此查询,是否可以使用我设置表格的方式?我可以回复所有写作诗歌的作者名单:

# to get authors who write poetry
 SELECT Authors.first_name, Authors.last_name
 FROM Authors 
 LEFT JOIN `author.genre` ON (Authors.authors_id  = `author.genre`.author_id)
 LEFT JOIN genre ON (`author.genre`.genre_id = genre.g_id)
 WHERE genre.genre = 'poetry'

数据库创建:

CREATE
TABLE Authors
(
authors_id INTEGER NOT NULL ,
first_name VARCHAR2 (16 CHAR) ,
last_name  VARCHAR2 (16 CHAR) ,
DOB        DATE ,
DOD        DATE
) ;
ALTER TABLE Authors ADD CONSTRAINT Authors_PK PRIMARY KEY ( authors_id ) ;

CREATE
TABLE "author.genre"
(
Authors_authors_id INTEGER NOT NULL ,
genre_g_id         INTEGER NOT NULL
) ;

CREATE
TABLE "authors.works"
(
works_ISBN         INTEGER NOT NULL ,
Authors_authors_id INTEGER NOT NULL
) ;

CREATE
TABLE genre
(
g_id  INTEGER NOT NULL ,
genre VARCHAR2 (32 CHAR) ,
descroptoin CLOB
) ;
ALTER TABLE genre ADD CONSTRAINT genre_PK PRIMARY KEY ( g_id ) ;

CREATE
TABLE sub_type
(
st_id      INTEGER NOT NULL ,
sub_type   VARCHAR2 (32 CHAR) NOT NULL ,
genre_g_id INTEGER NOT NULL
) ;
ALTER TABLE sub_type ADD CONSTRAINT sub_type_PK PRIMARY KEY ( st_id ) ;

CREATE
TABLE works
(
ISBN  INTEGER NOT NULL ,
Title VARCHAR2 (64 CHAR) NOT NULL ,
Description CLOB ,
num_pages INTEGER
) ;
ALTER TABLE works ADD CONSTRAINT works_PK PRIMARY KEY ( ISBN ) ;

CREATE
TABLE "works.genre"
(
works_ISBN INTEGER NOT NULL ,
genre_g_id INTEGER NOT NULL
) ;

ALTER TABLE "author.genre" ADD CONSTRAINT "author.genre_Authors_FK" FOREIGN KEY
( Authors_authors_id ) REFERENCES Authors ( authors_id ) ;

ALTER TABLE "author.genre" ADD CONSTRAINT "author.genre_genre_FK" FOREIGN KEY (
genre_g_id ) REFERENCES genre ( g_id ) ;

ALTER TABLE "authors.works" ADD CONSTRAINT "authors.works_Authors_FK" FOREIGN
KEY ( Authors_authors_id ) REFERENCES Authors ( authors_id ) ;

ALTER TABLE "authors.works" ADD CONSTRAINT "authors.works_works_FK" FOREIGN KEY
( works_ISBN ) REFERENCES works ( ISBN ) ;

ALTER TABLE sub_type ADD CONSTRAINT sub_type_genre_FK FOREIGN KEY ( genre_g_id
) REFERENCES genre ( g_id ) ;

ALTER TABLE "works.genre" ADD CONSTRAINT "works.genre_genre_FK" FOREIGN KEY (
genre_g_id ) REFERENCES genre ( g_id ) ;

ALTER TABLE "works.genre" ADD CONSTRAINT "works.genre_works_FK" FOREIGN KEY (
works_ISBN ) REFERENCES works ( ISBN ) ;

1 个答案:

答案 0 :(得分:0)

我认为这可以帮到你找到你想要的东西:

SELECT a.first_name, a.last_name, w.title
FROM Authors a
INNER JOIN "authors.works" aw
On a.authors_id = aw.Authors_authors_id
INNER JOIN works w
On aw.works_ISBN = w.ISBN
INNER JOIN "works.genre" wg
On w.ISBN = wg.works_ISBN
INNER JOIN genre g
On wg.genre_g_id = g.g_id
INNER JOIN sub_type s
On g.g_id = s.genre_g_id
Where g.genre = 'poetry'
And s.sub_type = 'haiku';

看起来你有作者和书的流派。我使用上面的书籍类型,因为你要求的查询显示结果中的标题,这似乎更相关。