Here I have pizza
table
pizza_id | toppings |
---|---|
1 | 1,2,3,4,5,6,8,10 |
2 | 4,6,7,9,11,12 |
I would like to know toppings with each pizza_id in common. Most used toppings in both the pizza_id…, expected answer as below table
Pizza_id toppings
1 4,6
2 4,6
I have tried using JOINS but couldn’t satisfy the condition.
Could anyone please give me hint.
Thank you
2
Answers
Your db is not respecting 1NF:each table cell must contain a single value. The best way to do so is having
pizza_table
andtopping_table
with a N-to-N relationship. In this way there is a table containing thepizza_id
related with EVERY topping it have.Pizza table is formed as:
Topping table is formed as:
And N-to-N table will be:
In this table you can make all operation you need to get your data.
As already pointed out by everyone, you should not be storing comma separated values in a single cell like that.
But, to answer your question, assuming you are looking for the intersection of the toppings CSV for all pizzas, and you have a toppings table with (topping_id, name), you could do something like:
Given these pizzas:
The above query will return:
This is insanely inefficient and would be much better served by the junction table suggested by ElNicho.
If you switch to using a junction (N-to-N) table like
pizzas_toppings (pizza_id, topping_id)
, the query becomes:Make sure your junction table is indexed in both directions: