2012-07-25 98 views
0

存在沒有行我有四個(培訓相關)表檢查是否爲一個主鍵SQL

CAKETABLE 
CAKE  ICING 

RESERVEDSPRINKLES 
CAKE  SPRINKLE 

SPRINKLETABLE 
SPRINKLE CONSUMED 

ICINGTABLE 
ICING  CONSUMED 

每個餅具有正好3灑1個結冰。

我想查詢數據庫,並得到所有的蛋糕有1個糖衣和3個糖霜,既沒有結冰也沒有任何糖衣消費='1'。因此我們假設插入數據: INSERT INTO ICINGTABLE(vanilla,0),(chocolate,0);

INSERT INTO SPRINKLETABLE (red, 0), (blue, 0), (green, 0), (orange, 0), (purple, 0),(pink, 0); 

INSERT INTO CAKETABLE (cake1, vanilla), (cake2, chocolate); 

INSERT INTO RESERVEDSPRINKLES (cake1, red), (cake1, blue), (cake1, green), (cake2, orange), (cake2, purple), (cake2, pink); 

所以,現在我已經cake1香草糖霜和紅,藍,綠灑cake2有巧克力糖衣和橙色,紫色和粉紅色灑。

當我運行查詢,我希望它返回

CAKES 
cake1 
cake2 

僅當有在蛋糕沒有消耗部件,因此即使一個灑標記爲已消耗我想忽略從那個整個蛋糕查詢。 以下查詢完全用於結冰。

SELECT CAKE 
FROM CAKETABLE as c 
INNER JOIN (SELECT * FROM ICINGTABLE WHERE CONSUMED = '0') as i 
ON c.ICING = i.ICING; 

但是對於灑,我有麻煩。如果我使用同樣的技術上面,我的查詢將返回:

CAKE 
cake1 
cake1 
cake1 
cake2 
cake2 
cake2 

我可以消除與DISTINCT,而是因爲如果任何灑已經消耗=「0」它仍然是不正確的它表明蛋糕當我想要相反功能的時候列表(如果所有的消費物都消耗='0',則只顯示蛋糕)

如果有人對此有更好的標題名稱,那將不勝感激。我想不出任何描述性和簡短。

+1

ICINGTABLE(表一)沒有CAKE?你有N c.CAKE = i.CAKE;但是在你提供的CAKE架構中不是ICINGTABLE中的一列 – james31rock 2012-07-25 18:22:47

+0

這個蛋糕是謊言。 「也許黑色梅薩?哈哈!這是一個笑話。」 - GLaDOS – spencer7593 2012-07-25 19:12:55

+0

@ james31rock你說得對,我的錯。它應該加入ICING,因爲CAKETABLE和ICINGTABLE都有結冰。 – Grizz 2012-07-25 19:20:12

回答

1

您可以使用not exists要求不再結冰,灑消耗:

select cake 
from caketable c 
where not exists 
     (
     select * 
     from icingtable i 
     where i.cake = c.cake 
       and i.consumed = '1' 
     ) 
     and not exists 
     (
     select * 
     from sprinkletable s 
     where s.cake = c.cake 
       and s.consumed = '1' 
     ) 
0

假設一個蛋糕總會有整整三灑,你可以GROUP BY蛋糕和使用HAVING過濾不任何的蛋糕有3點未消費灑:

SELECT CAKE 
FROM CAKETABLE as C 
INNER JOIN (
    SELECT * FROM ICINGTABLE WHERE CONSUMED = '0' 
) as I ON C.CAKE = I.CAKE 
INNER JOIN (
    SELECT CAKE FROM SPRINKLETABLE 
    WHERE CONSUMED = '0' 
    GROUP BY CAKE 
    HAVING COUNT(*) = 3 
) as S ON C.CAKE = S.CAKE; 
0

我認爲下面你想要做什麼:

select ct.cake 
from caketable ct join 
    reservedsprinkle rs 
    on ct.cake = rs.cake join 
    sprinkletable st 
    on rs.sprinkle = st.sprinkle join 
    icingtable it 
    on ct.cake = it.cake 
where it.consumed = 0 
group by ct.cake 
having count(distinct rs.sprinkle) = 3 and 
     sum(case when st.consumed = 1 then 1 else 0 end) = 0 

這是蛋糕分組,然後將大部分條件放在HAVING子句中。通過數據庫設計,它看起來像蛋糕只能有一種結冰。我假設CAKE在CAKE表中是唯一的。