我已经设计了这个问题的答案(我将在最后发布),但我只是想知道是否有一种“更清洁”的方式来构建查询。
问题如下:
最新Philip Roth书的标题和年份是什么?您不能使用ORDER BY子句。编写一个SQL语句。使用子查询。不要以为你已经知道Philip Roth的AuthorId,BookId的最新书或最新一本书的发行年份。
数据库中的相关表格:
Books (BookId, Title, YearPublished)
Authors (AuthorId, FirstName, LastName)
WrittenBy (AuthorId, BookId)
我的解决方案:
SELECT Title, YearPublished
FROM Books NATURAL JOIN Authors NATURAL JOIN WrittenBy
WHERE YearPublished = (SELECT MAX(YearPublished)
FROM Books NATURAL JOIN Authors NATURAL JOIN WrittenBy
WHERE AuthorId = (SELECT AuthorId
FROM Authors
WHERE FirstName = 'Philip'
AND LastName = 'Roth'))
AND FirstName = 'Philip'
AND LastName = 'Roth';
我无法找到一种不再指定名字和姓氏的方法。否则,它只列出了与Philip Roth最新出版物同年出版的所有书籍。
此查询完美无缺。但是,有更清晰的方法来查询吗?
谢谢:)
(关于我正在使用哪个DBMS:这些是考试的一些复习练习。我们必须使用由大学创建和提供的一个。这是非常基本的SQL。比Access 2010更简单)
答案 0 :(得分:1)
使用NOT EXISTS
反半连接可以更简单:
SELECT b.Title, b.YearPublished
FROM Authors AS a
NATURAL JOIN WrittenBy AS w
NATURAL JOIN Books AS b
WHERE a.FirstName = 'Philip'
AND a.LastName = 'Roth'
NOT EXISTS (
SELECT 1
FROM Books AS b1
NATURAL JOIN WrittenBy AS w1
WHERE w1.AuthorId = a.AuthorId
AND b1.YearPublished > b.YearPublished
);
这个问题意味着每年只有一本书和作者 - 或者它会含糊不清(你会得到多行)。
答案 1 :(得分:1)
你可以写与
相同SELECT Title, YearPublished
FROM Books NATURAL JOIN Authors NATURAL JOIN WrittenBy
WHERE YearPublished = (SELECT MAX(YearPublished)
FROM Books b NATURAL JOIN Authors a NATURAL JOIN WrittenBy wby
WHERE a.FirstName='Philip' and a.LastName='Roth')
AND FirstName = 'Philip'
AND LastName = 'Roth';
此解决方案删除了一个子查询。