有没有办法去"拆分"一行分成多行?
我的问题是我有边缘表,其中patternID是边的id,而sourceStationID和targetStationID是边连接的id:
模式:
patternID | sourceStationID | targetStationID
1|1|2
2|1|6
3|1|3
4|1|4
5|4|6
6|5|6
我还有可以转移的枢纽表:
集线器:
hubID
4
5
我需要摆脱那些通过一个集线器连接电台1-> 6的数据模式ID。所以查询的结果应该是:
4
5
我是通过将模式表与hubs表连接并再次使用模式表来实现的,所以我得到:
patternID | sourceStationID | targetStationID | patternID | sourceStationID | targetStationID
4 | 1 | 4 | 5 | 4 | 6
如何将此行拆分为两行?
编辑: 这是我到目前为止使用的代码:
select t2a.patternID from
(
select * from `patterns`
join `hubs` on `targetStationID` = `hubID`
where `sourceStationID` = 1
) as t1a
join
(
select * from `patterns`
join `hubs` on `sourceStationID` = `hubID`
where `targetStationID` = 6
) as t2a
on t1a.hubID = t2a.hubID
union
select t1b.patternID from
(
select * from `patterns`
join `hubs` on `targetStationID` = `hubID`
where `sourceStationID` = 1
) as t1b
join
(
select * from `patterns`
join `hubs` on `sourceStationID` = `hubID`
where `targetStationID` = 6
) as t2b
on t1b.hubID = t2b.hubID;
它正在工作但我使用相同的选择两次。
答案 0 :(得分:0)
更新我的答案,希望更接近你想要的。据我了解你的问题,这似乎给你的要求。可以避免视图,而是在CTE中完成连接:
C:\Users\DDevienne>sqlite3
SQLite version 3.8.4.3 2014-04-03 16:53:12
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> create table edges (id integer primary key autoincrement, beg int, end int);
sqlite> insert into edges (beg, end) values (1, 2), (1, 6), (1, 3), (1, 4), (4, 6), (5, 6);
sqlite> create view edges2 as
...> select start.id as beg_id, start.beg as beg, start.end as hub, finish.id as end_id, finish.end as end
...> from edges start, edges finish
...> where start.end = finish.beg;
sqlite> .headers on
sqlite> select * from edges2;
beg_id|beg|hub|end_id|end
4|1|4|5|6
sqlite> create table hubs (id integer primary key);
sqlite> insert into hubs values (4), (5);
sqlite> with hub_edges(beg_id, beg, hub, end_id, end) as (
...> select edges2.* from edges2, hubs where edges2.hub = hubs.id
...> )
...> select beg_id as id, beg, hub as end from hub_edges
...> union all
...> select end_id as id, hub as beg, end from hub_edges;
id|beg|end
4|1|4
5|4|6
sqlite>
警告:这需要最新的SQLite(3.8.4.3),并且不适用于3.8.3.x