问题描述:

I have 3 database tables.

First one containing Ingredients, second one containing Dishes and the third one which is conecting both Ingredients and Dishes.

Adding data to those tables was easy but I faced a problem while trying to select specific content.

Reurning all ingredients for specific dish.

SELECT *

FROM Ingredient As I

JOIN DishIngredients as DI

ON I.ID = DI.IngredientID

WHERE DI.DishID = 1;

But If i try to query for dish Name and Description no matter what kind o join I use i always get number of results equal to number of used Ingredients. If i have 4 ingredients in my dish then select returns Name and Description 4 times, how can I modify my slect to select those values just once?

Here is result of my query (same as hawk's) if i try to select Name and Description. I am using MS SQL.

ID Name Description DishID IngredientID

-- -------------------- -------------------------------------------------------------------- ------ ---------

1 Spaghetti Carbonara This delcitious pasta is made with fresh Panceta and Single Cream 1 1

1 Spaghetti Carbonara This delcitious pasta is made with fresh Panceta and Single Cream 1 2

Kuzgun's query worked fine for me. However from your sugestions I see that I dont really need join between DishIngredient and Dish.

When I need Name and Descritpion I can simply go for

 SELECT * FROM Dish WHERE ID=1;

Wehn I need list of Ingredient I can use my above query.

网友答案:

If you need to display both dish details and ingredient details, you need to join all 3 tables:

SELECT * 
FROM Ingredient As I 
JOIN DishIngredients as DI 
     ON I.ID = DI.IngredientID 
JOIN Dish AS D
     ON D.ID=DI.DishID
WHERE DI.DishID = 1; 
网友答案:

If you don't care about ingredient,you don't have to use the table DishIngredient.Just use tale Dish.select * from dish d where d.id=1. If you want to know what the ingredient is ,the sql that you use just query the id of table ingredient.It's useless.Because of the design of your database ,a little redundancy is a must .

select * from dish d join dishingredient di on d.id=di.dishid join ingredient i on    
i.id=di.ingredientid where d.id=1

Of course,you will get number of results that contain dish's name and description. If you want to get the full information but the least redundancy,you can do it in two step:

select * from dish d where d.id=1;
select * from ingredient i join DishIngredient di on i.id=di.ingredientid where       di.dishid=1

In java ,you can write a class to represent a dish and a list to represent the ingredients it use.

public class Dish {
    BigDecimal id;
    String name;
    String description;
    List<Ingredient> ingredient;
}
class Ingredient{
    BigDecimal id;
    String name;
    .....
}
相关阅读:
Top