0

我正在测试计算组件总重量的 SQL 查询。这些是表结构:

这里我存放了父组件和子组件的key:

-- CREATE TABLES SECTION -------------------------------------------------

-- TABLE COMPONENT

CREATE TABLE COMPONENT(
  COMPONENTID NUMBER NOT NULL,
  FKCOMPONENTID NUMBER,
  COMPONENTSTATSID INTEGER NOT NULL
)
/

-- ADD KEYS FOR TABLE COMPONENT

ALTER TABLE COMPONENT ADD CONSTRAINT COMPONENTID PRIMARY KEY (COMPONENTID)

这里我存储了组件的 id 和权重:

CREATE TABLE COMPONENTSTATS(
  COMPONENTSTATSID INTEGER NOT NULL,
  COMPONENTTYPEID INTEGER NOT NULL,
  NAME VARCHAR2(200 ) NOT NULL,
  SERIALNUMBER VARCHAR2(150 ),
  WEIGHTKG NUMBER(14,4),
  SIZEWEIGHTMILIM NUMBER(14,4),
)
/

-- ADD KEYS FOR TABLE COMPONENTSTATS

ALTER TABLE COMPONENTSTATS ADD CONSTRAINT COMPONENTSTATSID PRIMARY KEY (COMPONENTSTATSID)
/

我想用组件创建树并使用 SQL 查询来计算所有组件的总重量。我做了这个 SQL 查询:

select c.componentid, nvl(cs.weightkg, 0) as componentkg,
 (case 
    when exists (select 1 from component where fkcomponentid = c.componentid) then
      (select sum(nvl(cs.weightkg, 0)) as kg FROM  component a, componentstats cs  where a.fkcomponentid is not null and cs.componentstatsid = a.componentstatsid and a.fkcomponentid = c.componentid)
 end) as childrenkg
 from component c, componentstats cs  
 where 
 cs.componentstatsid = c.componentstatsid
 and componentid = ?
 order by c.componentid;

但由于某种原因,我无法得到正确的结果。我只得到第一个父母的第一个孩子。目标是使用 COMPONENT 表获取所有子项和子项并计算权重。

你能帮我找出我错在哪里吗?

4

1 回答 1

1

您可以在 Oracle 中使用分层查询来返回组件树,请参阅http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm

select componentid,
         (select sum(cs.weightkg)
            from component c2, componentstats cs
           where c2.componentstatsid = cs.componentstatsid
               start with c2.componentid = c1.componentid
         connect by prior c2.componentid = c2.fkcomponentid) sum_weightkg
from component c1
start with c1.fkcomponentid is null
connect by prior componentid = fkcomponentid;

http://www.sqlfiddle.com/#!4/def0e/2

于 2013-01-30T13:48:13.510 回答