3个表及更多的SQL查询

时间:2014-10-13 17:08:13

标签: sql join

用于以下架构:

Publisher (name, phone, city), PK: name.
Book (ISBN, title, year, published_by, previous_edition, price), PK: ISBN, FK: published_by refs Publisher, previous_edition refs Book.
Author (SSN, first_name, last_name, address, income), PK: SSN.
Write (aSSN, bISBN), PK: (aSSN, bISBN), FK: aSSN refs Author, bISBN refs Book.
Editor (SSN, first_name, last_name, address, salary, works_for, book_count), PK: SSN, FK: works_for refs Publisher.
Edit (eSSN, bISBN), PK: (eSSN, bISBN), FK: eSSN refs Editor, bISBN refs Book.
Author_Editor (aeSSN, hours), PK: aeSSN, FK: aeSSN refs Author, aeSSN refs Editor.

这是正确的方法吗?如果没有,我可以得到一个提示(任何提示表示赞赏)?

Select author.first_name, author.last_name
From author 
JOIN edit
ON author.ssn=edit.essn
Join write
Where edit.bisbn=write.bisbn and edit.isbn is not null;

提供每本书的标题,年份和出版商名称以及该书编辑的名字和姓氏。

SELECT title, year, published_by, first_name, last_name
FROM Book, 
Join Edit on ISBN=eSNN
Join Editor on SSN=eSSN

提供作者姓氏既不是“史密斯”也不是“Doe”的书籍的标题。

SELECT title

FROM book inner join write 
On book.isbn=write.bisbn
Join author on write.aSNN=Author.SNN
WHERE Author.last_name=’Doe’ and Author.first_name=’Smith’ 

2 个答案:

答案 0 :(得分:0)

你很亲密。编写连接时,需要指定表名和列名,并对每个连接执行相同的操作。所以第二个例子就是这样的:

  

提供每本书的标题,年份和出版商名称   本书编辑的名字和姓氏。

SELECT book.title, 
       book.[year], 
       book.published_by, 
       editor.first_name, 
       editor.last_name 
FROM   book, 
       inner 
       JOIN edit 
         ON book.isbn = edit.bisbn 
       INNER JOIN editor 
               ON edit.essn = editor.ssn

答案 1 :(得分:0)

虽然有一些ORM处理猜测要在更高级别加入的PK / FK,但在这个级别你通常需要明确指定你想要哪些列的数据'匹配'上

SELECT b.title, 
       b.year, 
       b.published_by, 
       ed.first_name, 
       ed.last_name 
FROM   book b, 
       inner 
       JOIN edit e 
         ON b.isbn = e.bisbn 
       JOIN editor ed
         ON e.essn = ed.ssn

希望这有帮助!