在连接表中查找只有一行的记录

时间:2013-10-02 13:02:51

标签: sql sql-server

recipe_food_xref
recipe_id int
food_id int

需要在recipe_food_xref中找到一条记录,其中食谱只有一种食物,食物是特定食物。

它与自身完美结合:

SELECT x1.recipe_id FROM recipe_food_xref x1
INNER JOIN recipe_food_xref x2 ON x2.recipe_id = x1.recipe_id
WHERE x1.food_id = 1
GROUP BY x1.recipe_id
HAVING COUNT(x2.recipe_id) = 1

这看起来有点难看,我想知道是否有更好的方法。

这是一个包含一些示例数据的SqlFiddle。基本上我想找到recipe_id:1,因为它有food_id:1并且没有多个food_id

http://sqlfiddle.com/#!3/6d474/1

4 个答案:

答案 0 :(得分:2)

SELECT recipe_id 
FROM recipe_food_xref
GROUP BY recipe_id
HAVING sum(case when food_id = 1 then 1 else 0 end) = 1
and sum(case when food_id <> 1 then 1 else 0 end) = 0

SQLFiddle demo

答案 1 :(得分:1)

这是我第一次去:

SELECT recipe_id
FROM recipe_food_xref
GROUP BY recipe_id
HAVING COUNT(food_id) = 1 AND SUM(food_id) = 1;

请注意,常规格式为HAVING COUNT(FOOD_ID) = 1 AND SUM(FOOD_ID) = <food id>。这是有效的,因为如果只有一个food_id,则总和等于id。

似乎与Juergen的答案类似,但更简单。我错过了什么吗?

我还尝试了以下操作,它必须额外扫描表格,但因为我之前从未使用ALL关键字,所以我觉得它很有趣。

SELECT recipe_id
FROM recipe_food_xref AS r
WHERE 1 = ALL (SELECT food_id FROM recipe_food_xref WHERE r.recipe_id=recipe_id);

http://sqlfiddle.com/#!3/6d474/26

答案 2 :(得分:0)

select *
from recipe_food_xref x
where not exists (
                   select i.food_id
                   from recipe_food_xref i
                   where i.recipe_id = x.recipe_id and
                         i.food_id <> x.food_id
                 ) 
-- if this is omitted you get all recipes having just one food:
      and x.food_id = 1

答案 3 :(得分:0)

以下是我对问题的解释:

  

查找所有含有单一成分的食谱。在这些配方中,找到单一成分为X

的配方
SELECT recipe_id
     , Max(food_id) As food_id
     , Count(*) As number_of_ingredients
FROM   recipe_food_xref
GROUP
    BY recipe_id
HAVING Count(*) = 1
AND    Max(food_id) = 1