2014-04-22 73 views
0

有沒有一種方法來「分裂」一行到多行?SQLite的「分裂」行成多行

我的問題是,我有邊緣的表,其中patternID是邊緣和sourceStationID和targetStationID是邊緣連接ID的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的那些數據patternIDs的。因此,查詢的結果應該是:

4 
5 

我這樣做,通過集線器表模式表連接模式表,並再次所以我得到:

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

我想你正在尋找的是WITH子句,遞歸statments。在近的例子是:http://social.msdn.microsoft.com/Forums/sqlserver/en-US/cd37dd9f-17c5-4df5-b072-5a9e51d1798d/show-all-children-and-grandchildren-for-parent-hierarchically ?forum = transactsql – user2346536

+0

爲什麼結果4和6?它不應該是4和5嗎?你說他們是模式ID。 – Frazz

回答

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

+0

有跟我描述,因爲我使用patternID作爲另一個表的外鍵結構化數據是很重要的。 – Mishak