查询返回多个相同的行而不是

时间:2016-05-28 05:05:34

标签: sql postgresql

我有表格:juicesjuice_ingredientsingredients

juices表具有以下属性:

  • 名称
  • 条形码

juice_ingredients表具有以下属性:

  • juice_id
  • ingredient_id

ingredients表有

  • 名称
  • 可选(布尔值)

为了客户的物流,各种果汁可能具有相同的条形码,但具有不同的成分,其中一些是可选的 我需要通过条形码选择其成分中不含任选成分的单一果汁。

我注册了四种成分:水(可选:假),糖(可选:真),菠萝果肉(可选:假)和薄荷(可选:真)。并注册了四种果汁:一种只用水和菠萝果肉,另一种用水,菠萝果肉和糖,另外用水,菠萝果肉和薄荷,还有水,菠萝果肉,薄荷和糖。所有条形码都相同。我询问是否只选择含有非选择性成分的果汁,在这种情况下是水和菠萝果肉。

SELECT *
FROM juices
INNER JOIN juice_ingredients ON (juice_ingredients.juice_id = juices.id)
INNER JOIN ingredients ON (juice_ingredients.ingredient_id = ingredients.id)
WHERE juices.barcode = '000000000001' AND ingredients.optional = false

但它返回了多行。什么应该改变这个查询只带一个,或组成中不含任选成分的果汁?

2 个答案:

答案 0 :(得分:2)

您可以使用having子句执行此操作:

SELECT juices.*
FROM juices
JOIN juice_ingredients ON juice_ingredients.juice_id = juices.id
JOIN ingredients ON juice_ingredients.ingredient_id = ingredients.id
WHERE juices.barcode = '000000000001'
GROUP BY 1, 2
HAVING MAX(ingredients.optional::text) = 'false'

答案 1 :(得分:1)

由于您未指定所使用的数据库,因此可能需要调整特定数据库的SQL:

select *
  from juices j
 where j.barcode = '000000000001'
   and not exists (select *
                     from juice_ingredients ji
                    inner join ingredients i
                       on (i.ingredient_id = ji.ingredient_id
                      and i.optional = true)
                    where ji.juice_id = j.juice_id)
相关问题