如何 select 包含特定记录引用的有向和无向链接

How to select directed and undirected links that contain a specific record reference

有两个 table:M_LINKM_LINK_DATA

CREATE TABLE M_LINK (
    ID             INTEGER NOT NULL,
    ISDIRECTED     SMALLINT DEFAULT 0 NOT NULL CHECK (ISDIRECTED IN (0,1))
);

CREATE TABLE M_LINK_DATA (
    ID           INTEGER NOT NULL,
    LINKREF      INTEGER NOT NULL,            -- reference to any record of table M_LINK
    MAINRECREF   INTEGER DEFAULT -1 NOT NULL, -- reference to any record of some third table
    SUBRECREF    INTEGER DEFAULT -1 NOT NULL  -- reference to any record of some third table
);

我想 select M_LINK_DATA 的所有 SUBRECREF 其中 LINKREFM_LINK 和 [=23] 的特定记录 :linkref =] 是某个第三 table 的特定记录 :recref。到目前为止,还不错。

这是我的 SQL 声明:

select SUBRECREF
  from m_link_data
  where LINKREF = :linkref and
        MAINRECREF = :recref

此外,如果 M_LINK 的记录 :linkrefISDIRECTED 等于 0,结果还应该包含 M_LINK_DATA 的每个 MAINRECREF其中 SUBRECREF 是已知第三个 table.

的相同特定记录 :recref

示例数据

-----M_LINK----
ID | ISDIRECTED
---+-----------
 1 |          1
 2 |          0

-------------M_LINK_DATA-------------
ID | LINKREF | MAINRECREF | SUBRECREF
---+---------+------------+----------
 3 |       1 |         10 |        11
 4 |       1 |         10 |        12
 5 |       1 |         13 |        10
 6 |       2 |         10 |        11
 7 |       2 |         14 |        11
 8 |       2 |         13 |        10
 9 |       2 |         15 |        10

期望输出

对于 :linkref = 1:recref = 10:

RECREF
------
    11
    12

对于 :linkref = 2:recref = 10:

RECREF
------
    11
    13
    15

如您所见,应该只有一个结果列,包含 MAINRECREFSUBRECREF

请帮助我扩展我的 SQL 查询以考虑 M_LINK.ISDIRECTED

我不确定我是否理解正确,但此过程 returns 期望的结果:

create or alter procedure NEW_PROCEDURE_2 (
    LINKREF integer,
    RECREF integer)
returns (
    O_SUBRECREF integer)
as
declare variable V_MAINRECREF integer;
BEGIN
  FOR
    select 
        t.subrecref,t.mainrecref
    from m_link_data t
    where 
       (
          (linkref = :linkref)
       and 
          (mainrecref = :recref)

       or
      (
      (linkref = :linkref)
      and
      ((select t1.isdirected from m_link t1 where (t1.ID = :linkref)) = 0)
      and 
      (t.SUBRECREF = :recref)
      )

       )
    INTO :o_subrecref,
         :v_mainrecref
  DO
  BEGIN
    if (:o_subrecref = :recref) then  o_subrecref = :v_mainrecref;
    SUSPEND;
  END
END

通过在主方向查询和反向查询之间使用联合,您可以使用单个查询来完成此操作,而无需求助于存储过程。

with directed_links as (
    select ld.linkref, ld.mainrecref as origin, ld.subrecref as target
    from m_link_data ld
    union all
    select ld.linkref, ld.subrecref as origin, ld.mainrecref as target
    from m_link_data ld
    inner join m_link l on l.id = ld.linkref
    where l.isdirected = 0
)
select target
from directed_links
where linkref = :linkref and origin = :recref