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

标签 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

最佳答案

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

关于sql - 查找连接表中只有一行的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19137573/

相关文章:

php - Like 语句匹配字符串的一部分

mysql - 我想根据 where 子句在不同列上显示一列数据总和

SQL Server 消息 241,级别 16,状态 1,从字符串转换日期和/或时间时转换失败

sql - SQL Server 中两个计数的总和

c# - 在 LINQ to SQL 中创建按位运算符?

sql - 如何将 .bak 文件导入 Microsoft SQL Server 2012?

sql-server - 检查 XML 元素是否在 SQL 中标记为 `xsi:nil`

sql - 查找具有匹配行的组

sql - 左连接没有结果

php - Codeigniter 和 SQL/Haversine 公式