0

我有四个(相关)表

CAKETABLE
CAKE      ICING

RESERVEDSPRINKLES
CAKE      SPRINKLE

SPRINKLETABLE
SPRINKLE  CONSUMED

ICINGTABLE
ICING     CONSUMED

每个蛋糕正好有 3 次洒水和 1 次糖霜。

我想查询数据库并获取所有具有 1 个糖衣和 3 个糖衣的蛋糕,其中糖衣和任何糖衣都没有 CONSUMED = '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);

所以现在我有一个带有香草糖衣和红色、蓝色、绿色糖衣的蛋糕 1 和带有巧克力糖衣和橙色、紫色和粉红色糖衣的蛋糕 2。

当我运行查询时,我希望它返回

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' 时显示)

如果有人对此有更好的标题名称,将不胜感激。我想不出任何描述性和简短的东西。

4

3 回答 3

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'
        )
于 2012-07-25T18:21:38.647 回答
0

假设一个蛋糕总是恰好有 3 次洒水,您可以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;
于 2012-07-25T18:23:15.460 回答
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 表中是唯一的。

于 2012-07-25T18:41:34.480 回答