Sql-Server
同一欄位上的兩個內連接以獲取相同的數據
我正在
SSRS
為MS CRM 2011
.有一個名為的表
StringMapBase
,其中包含Option Set
我們在不同的entities
. 該表有Value
和AttributeValue
列。我在任何實體中創建的每個選項集都在表中具有值(這是它的名稱)和屬性值(這是我為該選項集選擇的名稱)StringMapBase
。如果我命名了一個選項集,我應該從 StringMapBase 中讀取名稱。像這樣 :select SalesOrder.new_Order_Code, orderreceiptstep.new_NextFollow, orderreceiptstep.new_realization, StringMapBase.Value, orderreceiptstep.AccountIdName, orderreceiptstep.TotalReceivableAmount, orderreceiptstep.name, orderreceiptstep.DueDate, orderreceiptstep.ReceiptStepTypeIdName, StringMapBase.Value, from orderreceiptstep inner join StringMapBase on (orderreceiptstep.OrderReceiptStepStatus=StringMapBase.AttributeValue and StringMapBase.LangId=1065)
它給了我一個選項集的名稱。現在,問題是我在同一個實體上設置了另一個選項,應該得到它的名稱。這意味著我需要另一個
Inner Join
像上面一樣,像這樣:inner join StringMapBase on (orderreceiptstep.OrderReceiptStepPrioriy=StringMapBase.AttributeValue and StringMapBase.LangId=1065)
在第一個我使用
orderreceiptstep.OrderReceiptStepStatus
的orderreceiptstep
表中,在第二個我orderreceiptstep.OrderReceiptStepPrioriy
在Inner Join
子句中使用。我想讓這兩個連接在同一個欄位上,像這樣:
select SalesOrder.new_Order_Code, orderreceiptstep.new_NextFollow, orderreceiptstep.new_realization, StringMapBase.Value, orderreceiptstep.AccountIdName, orderreceiptstep.TotalReceivableAmount, orderreceiptstep.name, orderreceiptstep.DueDate, orderreceiptstep.ReceiptStepTypeIdName, StringMapBase.Value, from orderreceiptstep inner join StringMapBase on (orderreceiptstep.OrderReceiptStepStatus=StringMapBase.AttributeValue and StringMapBase.LangId=1065) inner join StringMapBase on (orderreceiptstep.OrderReceiptStepPrioriy=StringMapBase.AttributeValue and StringMapBase.LangId=1065)
這意味著
StringMapValue
在第一個應該返回一些東西,而在第二個 Inner Join 中必須返回另一個東西。我怎樣才能做到這一點?
啊,你就在那兒。
如果使用別名會更容易。SQL Server 需要某種方法來區分錶的副本。
select o.*, s1.Value, s2.Value from orderreceiptstep o inner join StringMapBase s1 on o.OrderReceiptStepStatus=s1.AttributeValue inner join StringMapBase s2 on o.OrderReceiptStepPrioriy=s2.AttributeValue where s1.LangID = 1065 and s2.LangID = 1065
使用這樣的 cte,您可能會獲得更好的性能:
with StringMaps as (select AttributeValue, Value from StringMapBase where LangID = 1065) select o.*, s1.Value, s2.Value from orderreceiptstep o inner join StringMaps s1 on inner join StringMapBase on o.OrderReceiptStepStatus=s1.AttributeValue inner join StringMaps s2 on o.OrderReceiptStepPrioriy=s2.AttributeValue