簡體   English   中英

查詢返回多個相同的行而不是一個

[英]Query returning multiple identical rows instead one

我有桌子: juicesjuice_ingredientsingredients

juices表具有以下屬性:

  • 名稱
  • 條碼

juice_ingredients表具有以下屬性:

  • juice_id
  • Ingredient_id

ingredients表有

  • 名稱
  • 可選(布爾值)

為了客戶的物流,各種果汁可能具有相同的條形碼,但是具有不同的成分,其中一些是可選的,我需要通過條形碼選擇在成分中不包含可選成分的單一果汁。

我簽了四種成分:水(可選:false),糖(可選:true),菠蘿肉(可選:false)和薄荷(可選:true)。 並簽署了四種果汁:一種僅與水和菠蘿果肉一起使用,另一種與水,菠蘿果肉和糖一起使用,另一種與水,菠蘿果肉和薄荷一起,另一種與水,菠蘿果肉,薄荷和糖一起使用。 全部具有相同的條形碼。 我進行查詢以僅選擇具有非可選成分的果汁,在這種情況下為水和菠蘿果肉。

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

但是它返回了多行。 應該如何更改此查詢以僅獲取一個查詢,或者組合物中不包含可選成分的果汁?

您可以使用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'

由於未指定要使用的數據庫,因此可能必須針對特定數據庫調整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