2017-09-14 68 views
0

引用的所有學生,讓我有名字和SID,它涉及到的SID表購買學生表。買家還有一個bookno字段,它與表格引用中的bookno相關(引用)。 Cites有一個與bookbook中的bookno相關的引用bookno字段。SQL查詢誰購買一本書,是由一本書,是更高的價格

現在我只有誰購買一本書,所有的學生,但希望完善它,只顯示那些誰買了一本書,是由至少一本書具有更高的性價比引學生。我不確定如何在這裏寫入計數查詢。任何幫助,將不勝感激。謝謝!

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

請問您的表格是否有價格欄?你能向我們展示完整的結構嗎? –

+1

添加一些示例表格數據和預期結果 - 作爲格式化文本,而不是圖像。 – jarlh

回答

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 
          ) 
      ) 
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 
       );