2013-11-22 84 views
4

我很難找到這個查詢。我知道這給了我所有供應商的供應商名稱,供應商爲項目提供了所有的零件。但只是因爲我在網上找到了答案!這個SQL查詢是什麼意思?

select sname 
    from s 
    where not exists (select * 
         from p 
         where not exists (select * 
             from spj spjx 
             where s.sno = spjx.sno and 
               p.pno = spjx.pno 
             ) 
        ); 
+3

這是一個經典的[關係分割方法](https://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/)。找到沒有他們沒有供應的零件的所有供應商。 –

回答

4

它有助於重新格式化:

select sname from s       -- show all supplier names 
where not exists        -- that there is not 
     (select * from p      -- a part 
     where not exists      -- that is not 
      (select * from spj spjx   -- supplied 
       where s.sno = spjx.sno   -- by them 
       and p.pno = spjx.pno)); 

基本上是:選擇一切都SNAME,在沒有P所在地方沒有SPJ這樣SPJ匹配S和P。將每個圖層視爲一個過濾器。

結果看起來像一個關係部門,正如Martin在評論中指出的那樣。

1

你可以把它想象成集過濾集。有三組位置:

select * from spj spjx 
where s.sno = spjx.sno and 
    p.pno = spjx.pno 

select * from p 
where not exists ({previous set}) 

select sname from s 
where not exists ({previous set}) 

所以,你到處看​​,外集是由該組的結果進行過濾。

此外,完整性,當你看到這一點:

from spj spjx 

這相當於:

from spj AS spjx 

從而使spjx在這個例子中alias

0

與其說
的「顯示誰提供所有供應商部分」,
它說:
顯示對他們來說,沒有部分未由他們提供所有供應商」