2011-09-22 52 views
-1

在sql server 2005中,我如何獲得下面table3中的結果集?表3是通過組合Table 1和Table這樣創建:如何合併這些表格?

table1.empid
table1.ticket
table2.identid

和反對table1的更新加入到表2不起作用,因爲EMPID不是唯一的。如果需要增加到下一個table2.indentid如果該ID已被該僱員使用。

此外,下面的table3還沒有創建。這是從table1和table2生成的集合。我使用table3作爲生成集的外觀示例。

table1 
empid ticketid indentid 
1  7   20 
1  9   4 
2  9   21 

table2 
indentid empid 
90   1 
91   1 
92   2 

table3 
empid ticketid table1_indentid table2_identid 
1  7   20     90 
1  9   4     91 
2  9   21     92 
+1

只是一個評論和意見。從我讀到的這聽起來更像是一個糟糕的數據建模問題,而不是查詢問題。也許你應該考慮修改你的數據模型。 –

+0

你的問題很難理解。你是否試圖創建'table3'作爲table1和table2查詢的輸出?你插入有問題嗎? – Randy

+0

我只是試圖從table1和table2創建table3中顯示的數據。問題是empid不是獨一無二的。當我做table1和table2的更新/連接時,我得到兩次table2_identid = 90。所以在上面的表格3中,我沒有91.我在那裏有90個。 – 4thSpace

回答

1

table1和table2之間的唯一連接是empid
您的table3示例的第1行和第2行具有相同的empid,因此它們也應該具有相同的table2_identid。您的示例不正確,或者無法用現有數據查詢。


但也許這就是你想要的東西:
如果你加入像表,以便

SELECT empid, ticketid, t1.indentid as table1_indentid, t2.identid as table2_identid 
FROM table1 AS t1 
    INNER JOIN table2 AS t2 ON t1.empid = t2.empid 

你會得到

table3 
empid ticketid table1_indentid table2_identid 
1  7   20     90 
1  7   20     91 
1  9   4     90 
1  9   4     91 
2  9   21     92 
0

這是你所需要的:

select t1.empid, t1.ticketid, 
     t1.indentid as table1_indentid, 
     t2.indentid as table2_identid 
from table1 t1 
inner join table2 t2 on t1.empid = t2.empid 

你應該考慮然而,檢查您的數據結構。

+0

table3尚未創建。它是由table1和table2生成的集合。我修改了這個問題。 – 4thSpace

+0

拿出桌子3的一部分,我想你有OP的要求的一部分... – Randy

+0

急:) :)修復它 –