得到行我有表recipes2ingredients
如何從表
(id, recipe_id, ingredient_id)
和2的成分,例如1,2。我需要得到所有的recipe_id
where is ingredient_id = 1 and ingredient_id = 2
得到行我有表recipes2ingredients
如何從表
(id, recipe_id, ingredient_id)
和2的成分,例如1,2。我需要得到所有的recipe_id
where is ingredient_id = 1 and ingredient_id = 2
使用having和count以及在哪裏可以找到所有具有這兩種成分的食譜。
SELECT recipe_ID, count(Distinct ingredient_id)
FROM recipes2ingredients
WHERE ingredient_ID in (1,2)
GROUP BY recipe_id
HAVING count(Distinct ingredient_id) = 2
使用了不同的計數,因此如果偶爾列出一種成分,我們不會得到誤報。
where子句限制只是那些具有的成分的一個或多個配方和具有子句確保我們只有2
這種方法具有允許兩者where子句的優點和具有計數爲運行時提供的變量,而不必更改查詢結構。
假設它在DB服務器上使用;您可以使用。
select distinct r2i1.recipe_id from recipes2ingredients r2i1
join recipes2ingredients r2i2
on r2i1.recipe_id = r2i2.recipe_id
where r2i1.ingredient_id = 1
and r2i2.ingredient_id = 2;
因此,是ingredient_id有多個值?這不是一個好的數據庫設計,它違反了第一範式(1NF)。 – Edper 2014-09-04 17:57:35