有两个表格:M_LINK
和M_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
);
我想选择SUBRECREF
M_LINK_DATA
的所有LINKREF
,其中:linkref
是M_LINK
的特定记录MAINRECREF
,:recref
是特定记录第三个表的select SUBRECREF
from m_link_data
where LINKREF = :linkref and
MAINRECREF = :recref
。到目前为止,非常好。
这是我的SQL语句:
ISDIRECTED
此外,如果来自:linkref
的记录M_LINK
的{{1}}等于0
,则结果还应包含MAINRECREF
M_LINK_DATA
的{{1}} {}} { {1}}与已知第三表的特定记录SUBRECREF
相同。
示例数据
: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
或MAINRECREF
。
请帮我扩展我的SQL查询以考虑SUBRECREF
。
答案 0 :(得分:1)
I'm not sure if I understood correctly but this procedure returns the desired result:
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
答案 1 :(得分:1)
您可以使用单个查询执行此操作,而无需通过在主方向的查询和反向的查询之间使用联合来诉诸存储过程。
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