【问题标题】:How to display the name of the product and the item the item is part of in SQL如何在 SQL 中显示产品名称和该项目所属的项目
【发布时间】:2014-11-28 04:30:32
【问题描述】:

我有两张表,一张叫items,一张叫components。 items 表具有以下属性:

  • 项目(例如 1、2、3、4、5)
  • 类别(例如水果、蔬菜、肉类、奶制品)
  • 名称(例如苹果、胡萝卜、沙拉盒、梨、香蕉)
  • 重量(例如 500 克)
  • 描述(例如一个苹果)
  • 价格(例如 1.00)

且components表有以下属性:

  • 组件(例如 1、2、3、4、5)
  • 部分(引用项目表的项目主键)(例如 5、6、1、9、10)
  • 项目(它引用项目表的项目主键)(例如 15、7、3、2、6)

这个想法是 items 表包含单个项目,例如苹果,以及包含许多其他项目的盒子,例如水果盒,组件表用于链接哪些项目是盒子中的零件,例如苹果是水果盒的一部分。

我想要做的是运行一个查询,该查询将显示作为盒子中组件的项目的名称,以及盒子的名称。

到目前为止,我可以运行以下查询:

 select 
      *
   from
      lbs_items
      join lbs_components using (item)
Which shows the names of the different boxes, but not what items are in them. And this query:
   select 
      *
   from
      lbs_components
      , lbs_items
   where
      lbs_components.part = lbs_items.item

其中显示属于框的项目,但不显示它们属于哪些框。

任何人有任何可以提供帮助的想法吗?

【问题讨论】:

标签: sql oracle select join rows


【解决方案1】:

正如 James 在评论中所解释的,您需要在此处加入 hierarchical query

类似的东西:

select LEVEL, items.* from items left join components on items.item = components.item
start with items.name='dessert'
connect by components.part = prior items.item;

鉴于样本数据:

create table items (item number(3), name varchar2(80));

insert all
  into items (item,name) values (1, 'apple')
  into items (item,name) values (2, 'pear')
  into items (item,name) values (3, 'fruit box')
  into items (item,name) values (4, 'cheese')
  into items (item,name) values (5, 'dessert')
  into items (item,name) values (6, 'fried chicken')
select * from dual
;

create table components as (select 1 item, 3 part from dual
                       union all select 2, 3 from dual
                       union all select 3, 5 from dual
                       union all select 4, 5 from dual);

这将产生:

LEVEL   ITEM    NAME
1       5       dessert
2       3       fruit box
3       1       apple
3       2       pear
2       4       cheese

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2011-04-21
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    相关资源
    最近更新 更多