SQL Query适用于所有购买图书的学生,这本书的价格较高

时间:2017-09-14 08:25:16

标签: sql postgresql

所以我有一个名字和sid的学生表,这与表购买中的sid有关。购买还有一个bookno字段,涉及表引用(引用)中的bookno。引用有一个quotbooknono字段,与表格书中的bookno有关。

现在我只有所有已经购买过书籍的学生,但是想要对其进行改进,以便只展示那些购买了至少有一本书价格更高的书籍的学生。我不确定如何在这里编写计数查询。任何帮助,将不胜感激。谢谢!

SELECT DISTINCT s.sid, s.sname
FROM student s
WHERE s.sid IN (SELECT r.sid 
    FROM buys r
    WHERE b.bookno IN (SELECT c.bookno
               FROM cites c
                   WHERE c.citedbookno IN (SELECT b.bookno 
                           FROM book b
                           WHERE b.bookno = c.citedbookno)));

2 个答案:

答案 0 :(得分:0)

简单版本:

select      distinct student.sid, student.sname
from        student
            inner join
            buys
            on  buys.sid = student.sid
            inner join
            book
            on  book.bookno = buys.bookno
            inner join
            cites
            on  cites.citedbookno = book.bookno
            inner join
            book bookExpensive
            on  bookExpensive.bookno = cites.bookno
where       bookExpensive.price > book.price

这是相同的,但可能表现更好:

select      student.sid, student.sname
from        student
where       exists(
                select      1
                from        buys
                            inner join
                            book
                            on  book.bookno = buys.bookno
                where       buys.sid = student.sid
                            and
                            exists(
                                select      1
                                from        cites
                                            inner join
                                            book bookExpensive
                                            on  bookExpensive.bookno = cites.bookno
                                where       cites.citedbookno = book.bookno
                                            and
                                            bookExpensive.price > book.price
                            )
            )

答案 1 :(得分:0)

假设cites.citedbookno是被引用书籍的bookno

SELECT 
    s.sid,
    s.sname
FROM Student s
WHERE s.sid IN (
                   SELECT r.sid 
                   FROM buys r 
                   JOIN cites c ON r.bookno = c.citedbookno 
               );