来自同一视图名称的多个连接与另一个视图名称

时间:2017-10-14 17:47:59

标签: sql

CREATE TABLE IF NOT EXISTS `SF` 
(
    `ref` int(6) unsigned NOT NULL,
    `extref` int(6) unsigned NOT NULL,
    `portfno` int(3) NOT NULL,
    `content` varchar(200) NOT NULL,
     PRIMARY KEY (`ref`)
) DEFAULT CHARSET=utf8;

INSERT INTO `SF` (`ref`, `extref`, `portfno`,`content`) 
VALUES ('100', '200', '999','SF1'),
       ('101', '200', '000','SF2'),
       ('102', '201', '999','SF3'),
       ('103', '201', '000','SF4');

CREATE TABLE IF NOT EXISTS `SEC` 
(
    `ref` int(6) unsigned NOT NULL,
    `extref` int(6) unsigned NOT NULL,
    `portfno` int(3) NOT NULL,
    `content` varchar(200) NOT NULL,
    PRIMARY KEY (`ref`)
) DEFAULT CHARSET=utf8;

INSERT INTO SECrefextrefportfnocontent)    价值观(' 100',' 200',' 999',' SEC1'),           (' 101',' 200',' 000',' SEC2'),           (' 102',' 201',' 999',' SEC3'),           (' 103',' 201',' 000',' SEC4');

我想要的输出如下2条记录。

Rec 1 ->100,200,999,sf1,100,200,999,sec1,101,200,000,sf2,101,200,000,sec2
Rec 2 ->102,201,999,sf3,102,201,999,sec3,103,201,000,sf4,103,201,000,sec4

我需要有一个不应该遇到性能问题的解决方案。

1 个答案:

答案 0 :(得分:0)

使用某种游标更容易。但是光标在性能上并不容易。用光标只填充一些临时表,应该很容易。

以下是没有光标的方法

select
 sf_odd.*
,sec_odd.*
,sf_even.*
,sec_even.*

FROM (SELECT *, Row_Number() OVER(ORDER BY ref) AS rn FROM sf) sf_even
join (SELECT *, Row_Number() OVER(ORDER BY ref) AS rn FROM sf) sf_odd
 on sf_odd.rn % 2 = 1
 and sf_even.rn % 2 = 0
 and sf_odd.rn = sf_even.rn + 1
Join (SELECT *, Row_Number() OVER(ORDER BY ref) AS rn FROM sec) sec_even
 on sec_even.rn % 2 = 0
 and sec_even.ref = sf_even.ref
join (SELECT *, Row_Number() OVER(ORDER BY ref) AS rn FROM sec) sec_odd
 on sec_odd.rn % 2 = 1
 and sec_odd.ref = sf_odd.ref