1

Menu表具有以下属性:

MEAL_ID
MEAL_NAME
MEAL_TYPE
ITEM1_ID
ITEM2_ID
ITEM3_ID
ITEM4_ID
ITEM5_ID
COST
ACTIVE_INDICATOR    

item表具有以下属性:

ITEM_ID
ITEM_NAME 
ACTIVE_INDICATOR

我正在尝试为表item_id中的每个实例打印每个项目的名称menu

select a.MEAL_ID, a.MEAL_NAME, a.MEAL_TYPE, b.ITEM_NAME, b.ITEM_NAME from mdw_meals_menu a, mdw_item_menu b where a.ITEM1_ID = b.ITEM_ID and a.Item2_ID= b.ITEM_ID and a.item3_id= b.ITEM_ID and a.item4_id = b.ITEM_ID and a.item5_ID= b.ITEM_ID;

这是我使用的代码,但它没有返回任何值。请帮忙

4

4 回答 4

1

您真的应该考虑将 Items 移动到不同的表中以规范化您的数据库。考虑有一个 Meal_Items 表,其中包含一个 Meal_Id 和一个 Item_Id——这样您就可以拥有与每餐相关联的 1-n 个项目。

但是,假设您想要 1 行包含所有项目名称,那么您需要将JOIN菜单表添加到每个项目的项目表:

SELECT m.Meal_Id, a.Meal_Name, a.Meal_Type, 
    i1.Item_Name Item_Name_1,
    i2.Item_Name Item_Name_2,
    i3.Item_Name Item_Name_3,
    i4.Item_Name Item_Name_4,
    i5.Item_Name Item_Name_5
FROM mdw_meals_menu m
   LEFT JOIN mdw_item_menu i1 ON m.Item1_Id = i1.Item_Id
   LEFT JOIN mdw_item_menu i2 ON m.Item2_Id = i2.Item_Id
   LEFT JOIN mdw_item_menu i3 ON m.Item3_Id = i3.Item_Id
   LEFT JOIN mdw_item_menu i4 ON m.Item4_Id = i4.Item_Id
   LEFT JOIN mdw_item_menu i5 ON m.Item5_Id = i5.Item_Id

我使用 aLEFT JOIN以防 Item 不存在,但您可以INNER JOIN根据您的数据只使用 an。

于 2013-05-25T12:39:40.737 回答
0

尝试这个...

SELECT  a.MEAL_ID ,
        a.MEAL_NAME ,
        a.MEAL_TYPE ,
        b.ITEM_NAME 
FROM    mdw_meals_menu a ,
        mdw_item_menu b
WHERE   b.ITEM_ID IN ( SELECT   ITEM1_ID
                   FROM     mdw_meals_menu
                   UNION
                   SELECT   ITEM2_ID
                   FROM     mdw_meals_menu
                   UNION
                   SELECT   ITEM3_ID
                   FROM     mdw_meals_menu
                   UNION
                   SELECT   ITEM4_ID
                   FROM     mdw_meals_menu
                   UNION
                   SELECT   ITEM5_ID
                   FROM     mdw_meals_menu )
于 2013-05-25T12:34:57.610 回答
0

我仍然认为你应该考虑重新设计你的表结构,但是......

SELECT m.meal_id, m.meal_name, m.meal_type, i1.item_name AS item_name1, i2.item_name AS item_name2
FROM mdw_meals_menu AS m
INNER JOIN mdw_item_menu AS i1 ON i1.item_id=m.item1_id 
INNER JOIN mdw_item_menu AS i2 ON i2.item_id=m.item2_id 
于 2013-05-25T12:39:19.830 回答
0

您可以通过执行五个连接将这些全部放在一行上:

select mm.MEAL_ID, mm.MEAL_NAME, mm.MEAL_TYPE, m1.ITEM_NAME, m2.ITEM_NAME,
       m3.item_name, m4.item_name, m5.item_name
from mdw_meals_menu mm left join
     mdw_item_menu mi1
     on mm.ITEM1_ID = mi1.ITEM_ID left join
     mdw_item_menu mi2
     on mm.ITEM2_ID = mi2.ITEM_ID left join
     mdw_item_menu mi3
     on mm.ITEM3_ID = mi3.ITEM_ID left join
     mdw_item_menu mi4
     on mm.ITEM4_ID = mi4.ITEM_ID left join
     mdw_item_menu mi5
     on mm.ITEM5_ID = mi5.ITEM_ID

此查询修复了您的连接语法和别名的使用(别名应该是表的缩写以增强可读性)。使用left join而不是inner join确保没有行丢失。这是标准语法,应该适用于任何数据库。

于 2013-05-25T12:39:21.613 回答