从文本创建SQL查询和代数表达式

时间:2012-02-23 18:27:51

标签: sql rdbms

根据任务,我有这些关系:

  • 部门(DepCode:pk,DepName,DepAdress)
  • LoanAccs(LoanAcc:pk,Name,DepCode:fk,Phone:ck)
  • Book(ISBN:pk,Copy:pk,Author,Titel,PublishedYear,BoughtYear)
  • LoanedBooks(ISBN:fk,Copy:fk,LoanDate:pk,LoanAcc:fk,Returndate)

由此,关系书中的ISBN定义了作者,标题和出版年份。对于LoanedBooks中ISBN,loanAcc和loanDate的每个组合,最多只能有一个副本。

然后我应该从任务中写一个SQL查询和一个代数表达式:

制作一个列表,显示所有尚未退回的四周以上的借书。该列表应包含贷款人的姓名和地址。还有书籍的作者和头衔。该列表应该在depAdress上排序,如果那些具有相同地址的列表,则在每个部门的loaners名称上。

我想出了一个看起来像这样的查询=>

SELECT 
    LoanAccs.name, Department.depAdress, book.author, book.title
LEFT OUTER JOIN 
    LoanedBooks ON loanAccs.loanAcc = loanedBooks.loanAcc
LEFT OUTER JOIN 
    Department ON loanAccs.depCode = department.DepCode
LEFT OUTER JOIN 
    Book ON loanedBooks.ISBN = books.ISBN
HAVING 
    (CURRENT_DATE - loanedbooks.returndate) <= 28
ORDER BY 
    depAdress, depCode, name desc;

我不太确定我是否正确设置了查询,因此任何评论/解释都会受到赞赏:)

另外,我想知道如何将其作为代数表达式写下来。如何开始,写作时要寻找什么。

1 个答案:

答案 0 :(得分:1)

试一试

SELECT LoanAccs.name
, Department.depAdress
, book.author
, book.title
LEFT OUTER JOIN LoanedBooks 
  ON loanAccs.loanAcc = loanedBooks.loanAcc
LEFT OUTER JOIN Department 
  ON loanAccs.depCode = department.DepCode
LEFT OUTER JOIN Book 
  ON loanedBooks.ISBN = books.ISBN
WHERE DATEDIFF(dd, CURRENT_DATE, loanedbooks.returndate) <= 28
ORDER BY depAdress, depCode, name desc