我有两张桌子
_id___|_description___
3433 | Apple-Pie
3699 | Strawberry-Pie
6952 | Banana-Pie
...
和
_cakeId__|_ ingredientCode _
3433 | SUGAR
3433 | APPLE
3433 | E_200_SRT_05
3433 | CREAM
3699 | SUGAR
3699 | STRABERRY
6952 | E_200_SRT_08
6952 | E_200_KJ_84
...
我现在想要在成分表中选择 0条的所有蛋糕(按id),而以E_
开头的成分不计算。
在上面的示例中,只会选择ID为 6952 的蛋糕。
我尝试了几种连接和子选择计数的组合,但我从来没有得到正确的结果
select
c.id
t1.cntIngr
from
cakes c
join (
select
cakeId,
count(ingredientCode) as cntIngr
from
cake_ingredients
group by cakeId
having ingredientCode not like 'E_%'
) as t1 on t1.cakeId = c.id
答案 0 :(得分:0)
http://sqlfiddle.com/#!9/d3d375/2
SELECT c.*
FROM cakes c
LEFT JOIN cake_ingredients i
ON i.cakeId = c.id
AND LEFT(i.ingredientCode,2)<>'E_'
WHERE i.cakeId IS NULL
答案 1 :(得分:0)
尝试此查询
SELECT description
FROM tab1
INNER JOIN (SELECT cakeId, COUNT(ingredientCode)
FROM tab2
WHERE ingredientCode NOT LIKE "E_%"
GROUP BY cakeId
HAVING COUNT(ingredientCode) = 0) AS tab2
ON tab1.id = tab2.cakeId
答案 2 :(得分:0)
这是一个不存在的查询:你想要所有没有非E成分的蛋糕:
select id
from cakes c
where not exists
(
select *
from cake_ingredients ci
where ci.ingredientcode not like 'E\_%' escape '\'
and ci.cakeId = c.id
);
与NOT IN:
相同select id
from cakes
where id not in
(
select cakeId
from cake_ingredients
where ingredientcode not like 'E\_%' escape '\'
);
(因为它的简单性,我通常更喜欢NOT IN而不是NOT EXISTS。)
答案 3 :(得分:0)