2016-08-29 51 views
0

我想創建嵌套聯接語句並使用別名編程目的。讓我給你一個我嘗試加入的表和他們的外鍵列表。這是一個有效的查詢嗎? (別名的重複)

TABLE1: id (Foreign key) 
TABLE2: id (primary key), idx (foreign key) 
TABLE3: id (primary key), idx (primary key) 
TABLE4: id (primary key), idx (primary key)` 

SELECT * 
FROM (((TABLE1 JOIN 
     TABLE2 
     ON TABLE1.id = TABLE2.id 
     ) AS NEW_TABLE JOIN 
     TABLE3 
     ON NEW_TABLE.id = TABLE3.id AND NEW_TABLE.idx = TABLE3.idx 
    ) AS NEW_TABLE JOIN 
     TABLE4 
     ON NEW_TABLE.id = TABLE4.id AND 
     NEW_TABLE.idx = TABLE4.idx 
    ); 

你能告訴我,如果這是一個有效的查詢,並使用別名這種方式的作品?

+2

你有你使用特定的DBMS? – Zi0n1

+0

是的,SQL Server – sethu

回答

0

你可能需要窩完整查詢:

SELECT * FROM 
    (SELECT * FROM 
    (SELECT * FROM TABLE1 JOIN TABLE2 ON TABLE1.id = TABLE2.id) A 
    JOIN TABLE3 ON A.id = TABLE3.id AND A.idx = TABLE3.idx) B 
    JOIN TABLE4 ON B.id = TABLE4.id AND B.idx = TABLE4.idx; 

雖然,不知道該表的內容很難說,你可能會得到什麼樣的結果,或者你的查詢是否是有效的,甚至。

1

我不這麼認爲。我會寫這樣的:

SELECT * 
FROM TABLE1 JOIN 
    TABLE2 
    ON TABLE1.id = TABLE2.id JOIN 
    TABLE3 
    ON TABLE1.id = TABLE3.id AND TABLE2.idx = TABLE3.idx 
    TABLE4 
    ON TABLE1.id = TABLE4.id AND 
     TABLE2.idx = TABLE4.idx; 

(嗯,事實上,我會用表的別名,但是這是想法)

括號沒有爲你做任何事情。我也認爲重新使用NEW_TABLE別名很可能會產生錯誤。

0

格式像下面..

SELECT * FROM 
    TABLE1 
    JOIN TABLE2 ON TABLE1.id = TABLE2.id 
    JOIN TABLE3 ON Table1.id = TABLE3.id 
     AND Table2.idx = TABLE3.idx 
    JOIN TABLE4 ON Table3.id = TABLE4.id 
     AND Table3.idx = TABLE4.idx