2017-12-18 172 views
2

我命名節點的兩個表格和鏈接,就像這樣:內側連接兩次返回任何結果

--Links: 
----------------------------------- 
id fromx fromy tox  toy 
----------------------------------- 
a1  x1  y1  x2  y2 
a2  x2  y2  x3  y3 
a3  x2  y2  x4  y4 
a4  x1  y1  x4  y4 
a5  x1  y1  x5  y5 

--Nodes: 
id  x y 
-------------- 
1  x1 y1 
2  x2 y2 
3  x3 y3 
4  x4 y4 
5  x5 y5 

我想通過匹配fromx,弗羅米和TOX,玩具生產第三個表在打擊的節點表中的X和Y鏈接表產生一個表像這樣:

linkid fromid toid 
-------------------- 
    a1  1  2 
    a2  2  3 
    a3  2  4 
    a4  1  4 
    a5  1  5 

在努力達到那個結果,我用這個查詢使用上的節點表連接兩次以下查詢,但我沒有得到任何結果。

select links.id as linkid, 
n1.id as nodeid, fromx, fromy, tox from links 
inner join nodes n1 
inner join nodes n2 
on 
links.fromx = n1.x 
and links.fromy = n1.y 
and links.tox = n2.x 
and links.toy = n2.y 

我「很高興來創建臨時表或者這樣,如果這將有助於。

+0

這是一個有趣的問題。我重新創建你的數據,但我現在只能訪問SQL Server,因此我會盡量使用盡可能標準的語法。 –

+0

正如其他人所建議的那樣,它很可能與您的數據有關。如果運行命令行SQLite shell(sqlite3。 exe文件),你可以使用「.dump」來生成SQL語句率全部創建表並插入語句。如果您將該輸出添加到您的問題。其他人可以重現你的模式和數據。 – Fabian

回答

3
select 
     l.id as link_id, 
     frm.id as from_id, 
     t.id as to_id 
from 
     links l 
inner join 
     nodes frm 
     on frm.x = l.fromx 
     and frm.y = l.fromy 
inner join 
     nodes t 
     on t.x = l.tox 
     and t.y = l.toy 

SQL Fiddle

+0

非常感謝!這不幸的是不在sqlite中工作,但我不知道爲什麼。 (我正在使用SQLiteStudio來測試它)。運行時查詢不會返回任何內容。 :( –

+0

我在SQL Server中使用了基本相同的查詢,並得到了正確的結果 –

+0

@PatJones我完全理解,jophab也發佈了一個鏈接到SQL Fiddle,它在MySql上運行正常,我認爲它必須與SQLite那麼? –