Relacja jeden do wielu szukanie

0

Mam trzy tabele w bazie:

dishes
+---------+--------+
| pizza_id| pizza |
+---------+--------+
| 1 | pizza |
| 2 | pizza2 |
+---------+--------+

ingredients
+--------------+-------------------+
| ingredient_id| ingredient |
+--------------+-------------------+
| 1 | tomato |
| 2 | cheese |
+--------------+-------------------+

I tabela łącząca:

+------------------------+-------------------+-------------+
| ingredient_to_dish_id| ingredient_id | dish_id |
+------------------------+-------------------+-------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
+------------------------+-------------------+-------------+

Jak teraz pobrać wszystkie pizze które zawierają konkretne składniki czyli np wszystkie pizze które maja ser i szynkę itp

0

Tak na szybko przyszły mi do głowy takie dwa pomysły:

select dishes.pizza
from dishes inner join ingredient_to_dish
on dishes.pizza_id = ingredient_to_dish.dish_id
where ingredient_to_dish.ingredient_id in
(
 select ingredients.ingredient_id
 from ingredients
 where ingredients.ingredient in ('tomato', 'cheese')
)
group by dishes.pizza
select dishes.pizza
from dishes
where dishes.pizza_id in
(
 select ingredient_to_dish.dish_id
 from ingredient_to_dish
 where ingredient_to_dish.ingredient_id in
 (
  select ingredients.ingredient_id
  from ingredients
  where ingredients.ingredient in ('tomato', 'cheese')
 )
)
0

Nie do końca jest tak jakbym chciał ponieważ będą wtedy dania która maja sam ser i takie które maja ser i pomidora a chciałbym tylko takie które maja i ser i pomidora

0

Select d.pizza_id,d.pizza
from dishes as d
inner join ingredients_to_dish as i
on d.pizza_id=i.pizza_id
inner join ingredients as ing
on i.ingredient_id=ing.ingredient_id
where ing.ingredient='cheese' or ing.ingredient='tomato'
group by d.pizza_id,d.pizza
having count (*) =(
Select max(theCount) from (
Select count(d.pizza_id)as theCount
from dishes as d
inner join ingredients_to_dish as i
on d.pizza_id=i.pizza_id
inner join ingredients as ing
on i.ingredient_id=ing.ingredient_id
where ing.ingredient='cheese' or ing.ingredient='tomato'
group by d.pizza_id,d.pizza) as b

)

Andrzej, jeżeli dobrze zrozumiałem o co Ci chodzi to powyższe zapytanie rozwiązuje Twój problem.Po pierwsze tworzysz joiny, implementujesz filtry i grupujesz.bez klauzuli having dostajesz te pizze które mają wszystkie składniki, jak również te pizze które mają tylko ser-Ty jak piszesz nie chcesz tego.W tym wypadku klauzula having rozwiązuje problem, ponieważ zwróci Ci tylko te pizze które mają wszystkie składniki.Testowałem to na SQL SERVER(syntax) i działa.
Pozdrawiam

0

Marcin,
Moje rozwiązanie działa w podobny sposób jak Twoje.Jedyna różnica jest taka, że w moim nie trzeba ręcznie wprowadzać liczby składników(Moja pierwsza myśl była dokładnie taka sama jak Twoja, żeby ręcznie wprowadzać wartość dla having) ;-)

Pozdrawiam

0

Super wielkie dzięki! Oto chodziło :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1