SQL连接提供更多行

SQL连接提供更多行,sql,sql-server,Sql,Sql Server,我有两张桌子 Table 1 PropertyId 1 2 3 4 5 6 Table 2 PropertyID PropertyCode PropList ID 1 2 45 3 4 67 5 6 89 Table 3 Property ID IType 1 3 2 11 3

我有两张桌子

Table 1

PropertyId

1
2
3
4
5
6

Table 2

PropertyID PropertyCode PropList ID

1            2            45
3            4            67
5            6            89

Table 3

Property ID  IType

1             3
2             11
3             3 
4             11
5             3
6             11

Target Table

PropertyID   PropertyCode

1             45
2             45
3             67
4             67
5             89
6             89
上面是我拥有的两个表的
Coln
表示

PropertyId
上的两个表连接时,我希望表2的
PropertyId
上的表连接,如果在
Table2.PropertyId
下找不到该值,则在
Table2.PropListId
处连接

我正在使用下面的查询进行此操作

SELECT  t1.*, t2.PropertyCode 
FROM    Test.dbo.DailyBudgetExtract T1 , Test.dbo.DailyPropertylListExtract T2 
WHERE   t1.propertyid = t2.proplistid 
OR      t1.propertyid = t2.propertyid
编辑。

如果存在另一个表3,则在联接时(
Table1.PropertyId=table3.PropertyId
),如果
Itype=3
,则在
PropertyId
上联接表2;如果
Itype=11
上联接


它工作得很好,但是表1对我来说有180000行,表2245行。当我运行查询时,它显示2450000行受影响。这里有什么不对吗?

如果您的数据被乘以,这可能是因为表2中的列中有重复项,或者在
propertycode
propertid
列之间重复了值。第一个问题在这种情况下处理起来有点痛苦。第二个可以用左外部联接处理

我假设您将
PropertyCode
PropertyList
列交换为
Table2
(基于示例数据)。以下是一个可能满足您需要的查询:

   SELECT  t1.*, coalesce(t2.PropertyCode, t3.PropertyCode) as PropertyCode
   FROM Test.dbo.DailyBudgetExtract T1 LEFT OUTER JOIN
        Test.dbo.DailyPropertylListExtract T2 
        ON t1.propertyid = t2.propertyid LEFT OUTER JOIN
        Test.dbo.DailyPropertylListExtract T3
        ON t1.propertyid = t3.proplistid ;

您需要建立到
DailyPropertylListExtract
表的两个联接,每个联接上都有适当的联接条件,然后从联接条件找到行的表中输出值

Select b.*,  
   Coalesce(p1.PropertyCode,  p2.PropertyCode) PropertyCode
FROM Test.dbo.DailyBudgetExtract b
   left Join Test.dbo.DailyPropertylListExtract p1
       On  p1.propertyid = b.propertyid 
   left Join Test.dbo.DailyPropertylListExtract p2
       On  p2.PropListId  = b.propertyid 

你不能像那样召唤用户-只有已经发表评论的用户才会在你
@
他们时得到通知。无论如何,这不是它的工作原理——不要(试图)纠缠特定的用户。我对表格做了一个小的编辑,并添加了另一个表格3作为条件。如果ProprtyId在表3中的对应值为3或11,则与表2的联接应选择要与ProprtyId或PropListId联接的列