2012-07-31 80 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' 
相关问题