检查主键SQL是否不存在行

时间:2012-07-25 18:17:40

标签: mysql sql select

我有四张(相关)表格

CAKETABLE
CAKE      ICING

RESERVEDSPRINKLES
CAKE      SPRINKLE

SPRINKLETABLE
SPRINKLE  CONSUMED

ICINGTABLE
ICING     CONSUMED

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

我想查询数据库并得到所有有1个糖衣和3个洒水的蛋糕,其中结冰和任何洒水都没有CONSUMED ='1'。

所以让我们的psuedo插入数据:     INSERT INTO ICINGTABLE(香草,0),(巧克力,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')

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

3 个答案:

答案 0 :(得分: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'
        )

答案 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;

答案 2 :(得分: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表中是唯一的。