2012-07-31 77 views
1

如何從一個查詢的結果中使用兩列來查找另一個表中的值?如何使用一個查詢結果中的兩列來查找另一個表中的值?

我看到了幾個「字典」問題的例子,使用單個列,像UserID查找用戶的名字和姓氏,但我有兩列需要匹配每個匹配的多個可能結果。

目前,我查詢所有準備好發貨爲TRUE的記錄,然後使用代碼循環查看每個產品/顏色梳理的運輸標籤文件的結果。我的目標是通過單個查詢獲得理想的結果。

我試過下面的SQL,但它太慢了(幾分鐘)。我想知道如果使用JOIN或其他一些技巧可能會使這個更快(不到一秒)。目前我的代碼需要~2秒。我使用的真實世界表格有幾千條記錄,並且會返回幾百條結果。

Select 
    tblA.BoxID, 
    tblA.Product, 
    tblA.Color, 
    tblA.Ready_to_Ship AS Ready, 
    tblB.Shipping_Label_File 
From 
    Table_A tblA, 
    Table_B tblB 
Where 
    tblB.Product = tblA.Product AND 
    tblB.Color = tblA.Color AND 
    tblA.Ready_to_Ship = 'TRUE' 


Desired results: 
BoxID Product  Color Ready Shipping_Label_File 
B5255 34xBty2001  Red TRUE ShipLBL-01r_A.txt 
B5255 34xBty2001  Red TRUE ShipLBL-01r_B.txt 
J6632 34xBty2002  Blue TRUE ShipLBL-07b_D.txt 
E2748 34xBty2002  Red TRUE ShipLBL-07r_D.txt 
E4716 64d_Dty2005 Red TRUE ShipLBL-05r_B.txt 
E4716 64d_Dty2005 Red TRUE ShipLBL-05r_C.txt 

Table_A 
BoxID Product  Color Ready_to_Ship 
B5255 34xBty2001 Red TRUE 
J6632 34xBty2002 Blue TRUE 
F8975 64b_Dty2005 Blue FALSE 
F9768 64b_Dty2005 Blue FALSE 
I1053 34xBty2001 Green FALSE 
J2202 34xBty2001 Blue FALSE 
D2986 64a_Dty2005 Blue FALSE 
A6210 64b_Dty2005 Blue FALSE 
I1088 34xBty2002 Blue FALSE 
E2748 34xBty2002 Red TRUE 
D7945 64b_Dty2005 Blue FALSE 
E4716 64d_Dty2005 Red TRUE 

Table_B 
Product  Color Shipping_Label_File 
34xBty2001 Red  ShipLBL-01r_A.txt 
34xBty2001 Red  ShipLBL-01r_B.txt 
34xBty2001 Blue ShipLBL-01b_A.txt 
34xBty2001 Green ShipLBL-01g_A.txt 
34xBty2001 Green ShipLBL-01g_C.txt 
34xBty2002 Red  ShipLBL-07r_D.txt 
34xBty2002 Blue ShipLBL-07b_D.txt 
34xBty2002 Green ShipLBL-07g_M.txt 
64a_Dty2005 Blue ShipLBL-A3b_A.txt 
64a_Dty2005 Green ShipLBL-A3g_E.txt 
64b_Dty2005 Red  ShipLBL-05r_B.txt 
64b_Dty2005 Red  ShipLBL-05r_C.txt 
64b_Dty2005 Green ShipLBL-05g_A.txt 
+0

你對錶的任何索引? – 2012-07-31 04:21:17

+0

BoxID是Table_A的pri鍵,但我不確定Table_B。 – LastDavid 2012-07-31 05:25:28

+0

Table_B的pri鍵是RowID – LastDavid 2012-07-31 05:27:29

回答

1

嘗試

Select 
    tblA.BoxID, 
    tblA.Product, 
    tblA.Color, 
    tblA.Ready_to_Ship AS Ready, 
    tblB.Shipping_Label_File 
From 
    Table_A tblA 
    left join Table_B tblB on tblA.Product=tblB.Product and tblA.Color=tblB.Color 
Where 
    tblA.Ready_to_Ship = 'TRUE' 
相關問題