简体   繁体   English

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

[英]Query returning multiple identical rows instead one

I have the tables: juices , juice_ingredients and ingredients . 我有桌子: juicesjuice_ingredientsingredients

The juices table has the attributes: juices表具有以下属性:

  • name 名称
  • barcode 条码

The juice_ingredients table has the attributes: juice_ingredients表具有以下属性:

  • juice_id juice_id
  • ingredient_id Ingredient_id

And the ingredients table has ingredients表有

  • name 名称
  • optional (boolean) 可选(布尔值)

For the sake of customer's logistics various juices may have the same barcode, but with different ingredients, some of which are optional I need select, by barcode, the single juice that has no contains optional ingredient among its ingredients. 为了客户的物流,各种果汁可能具有相同的条形码,但是具有不同的成分,其中一些是可选的,我需要通过条形码选择在成分中不包含可选成分的单一果汁。

I signed up four ingredients: water (optional: false), sugar (optional: true), pineapple pulp (optional: false) and mint (optional: true). 我签了四种成分:水(可选:false),糖(可选:true),菠萝肉(可选:false)和薄荷(可选:true)。 And signed up four juices: one only with water and pineapple pulp, other with water, pineapple pulp and sugar, other with water, pineapple pulp and mint, and other with water, pineapple pulp, mint and sugar. 并签署了四种果汁:一种仅与水和菠萝果肉一起使用,另一种与水,菠萝果肉和糖一起使用,另一种与水,菠萝果肉和薄荷一起,另一种与水,菠萝果肉,薄荷和糖一起使用。 All with the same barcode. 全部具有相同的条形码。 I make a query to select only the juice make with non optional ingredients, in this case water and pineapple pulp. 我进行查询以仅选择具有非可选成分的果汁,在这种情况下为水和菠萝果肉。

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

But it was returning multiple rows. 但是它返回了多行。 What should change this query to bring only one, or the juice containing no optional ingredients in the composition? 应该如何更改此查询以仅获取一个查询,或者组合物中不包含可选成分的果汁?

You could do it with a having clause: 您可以使用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'

Since you didn't specify which database you are using, you may have to adjust the SQL for your specific database: 由于未指定要使用的数据库,因此可能必须针对特定数据库调整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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM