2011-09-22 24 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

急:) :)修复它 –