2015-01-14 46 views
1

我很抱歉,如果這已經被問到,或者它是一個基本的概念 - 我沒有足夠的經驗在SQL知道如何簡潔地問它(因此我沒有太多的運氣搜索它)。如何編寫一個SQL查詢,該查詢檢索每個現有唯一ID組合的一行?

請參閱下面第一個片段中每個表格的第一行,瞭解我正在使用的表格。 Table1和Table3可以有多個具有相同table2Id的行。

最初,我只是使用Table1和Table2。我爲每個Table1檢索了一行,並且都很好。不過,我現在還需要從表3中檢索數據 - 我可以形容的影響的最好方法是使用下面的例子:

Table1: 
id table2Id otherData1 
abc 123  "otherData" 
def 123  "anotherData" 

Table2: 
id otherData2 
123 "yetAnotherData" 

Table3: 
id table2Id otherData3 
[email protected]# 123  "thereCouldntBeMoreData" 
$%^ 123  "iCantBelieveItsNotData" 

完全代表所有的數據,我需要4行,一個用於abc +!@#,一個用於abc + $%^,一個用於def +!@#,最後一個用於def + $%^。如果我正確地描繪這一點,我的最終結果將是什麼這個效果:

comboId t1.id t2.id t3.id t1.otherData1 t2.otherData2  t3.otherData3 
[email protected]# abc  123  [email protected]#  "otherData"  "yetAnotherData" "thereCouldn'tBeMoreData" 
abc$%^ abc  123  $%^  "otherData"  "yetAnotherData" "iCantBelieveItsNotData" 
[email protected]# def  123  [email protected]#  "anotherData" "yetAnotherData" "thereCouldn'tBeMoreData" 
def$%^ def  123  $%^  "anotherData" "yetAnotherData" "iCantBelieveItsNotData" 

我怎麼能做到這一點?並且預先感謝您提供的任何幫助,即使這只是指示我向其他人回答類似問題的方向。

+1

我想你會發現幫助,如果你搜索「笛卡爾加入」 –

+0

我不能給予好評,但仍然感謝你! – barium56

回答

1

正如WW所說,你需要一個笛卡爾連接。幸運的是,這是SQL中的默認連接。但是,由於您需要加入的列有不同的名稱,因此需要ON條款;您應該嘗試使您加入的列具有相同的名稱。

要創建comboId,您需要鏈接列;在SQL Server中執行該操作的語法是+,在Oracle |中,我認爲在MySql中有一個Concat()函數。每當你問一個關於SQL的問題時,總是告訴我們你正在使用哪個SQL。

在SQL Server中這將是:

SELECT t1.id+t3.id as comboId, 
     t1.id as 't1.Id', 
     t2.id as 't2.Id', 
     t3.id as 't3.Id', 
     t1.otherData1, 
     t2.otherData2, 
     t3.otherData3 
FROM Table1 t1 
    JOIN Table2 t2 ON t2.id=t1.table2Id 
    JOIN Table3 t3 ON t3.table2Id=t2.id 
+0

我還不行,但非常感謝! – barium56

0

這會讓你得到你想要的結果,但我會第一個說它最好的哈希,沒有主鍵和外鍵,我不太確定如何執行「文本書」連接操作。

SELECT t1.id+''+t3.id comboId,t1.id t1ID, t2.id t2ID, t3.id t3ID, t1.otherData1, t2.otherData2, t3.otherData3 
FROM table1 t1,table2 t2,table3 t3;