加入SQL语句优化

时间:2016-06-15 19:38:22

标签: sql join

我有两张桌子:

客户

ID
Customer_ID
Name
Sir_Name
Phone
Email

表格发票

Manager_Name
Manaer_First_Name
Customer_ID1
Customer_ID2
Customer_ID3

每位客户只有一个Customer.Customer_ID,或者客户没有Customer_ID

Invoice.Customer_ID1 中,我有几次 Customer_ID.Customer_ID

我想在Customer Table Join Invoice Table中获取所有记录 - 检查Customer_ID = Customer_ID1如果不是Customer_ID = Customer_ID2 Or Customer_ID = Customer_ID2

如果在其中一行中找到customer_ID,则停止搜索。

4 个答案:

答案 0 :(得分:1)

编写查询的最佳方式可能是:

select . . .
from customer c join
     invoice i
     on c.customer_id = coalesce(i.customer_id1, i.customer_id2, i.customer_id3);

这应该能够利用customer(customer_id)上的索引。如果效率不高,则另一种选择是left join

select . . ., coalesce(c1.col1, c2.col1, c3.col1) as col1, . . .
from invoice i left join
     customer c1
     on c1.customer_id = i.customer_id1 left join
     customer c2
     on c2.customer_id = i.customer_id2 left join
     customer c3
     on c3.customer_id = i.customer_id3;

left join 可以利用customer(customer_id)上的索引。您需要使用coalesce()中的select来选择右表中的字段。

答案 1 :(得分:0)

select
    *
from [Table Invoice] A
JOIN [Customer] B
    ON B.Customer_ID = A.Customer_ID1 OR (B.Customer_ID <> A.Customer_ID1 AND B.Customer_ID = A.Customer_ID2) OR (B.Customer_ID = A.Customer_ID3 AND B.Customer_ID <> A.Customer_ID2 AND B.Customer_ID <> A.Customer_ID1)

这将返回所有客户的所有发票。如果您只需要一位客户需要发票 - 添加

WHERE B.Customer_ID = @YourCustomerID

语句。如果您只需要一个,第一张发票,请添加“TOP 1&#39;选择陈述:

SELECT TOP 1

答案 2 :(得分:0)

可以是内部联接还是子句

 select Customer.*, Invocie.*
 from Customer
 inner join Invoice on ( Customer.Customer_ID = Invoce.Customer_ID1
   OR Customer.Customer_ID = Invoce.Customer_ID2 
   OR Customer.Customer_ID = Invoce.Customer_ID3)

答案 3 :(得分:0)

这就是我理解您的请求的方式:您希望所有在发票表中至少有一个条目的客户。但是每个客户,你想要的是最好的&#34;发票记录; ID1匹配优于ID2匹配,ID2匹配优于ID3匹配。

因此,请加入表格以获取所有匹配项,然后将匹配项与row_number进行排名,以获得最佳匹配记录#1。然后只保留排名第一的那些行。

select *
from
(
  select 
    c.*, 
    i.*,
    row_number() over 
    (
      partition by c.customer_id order by 
        case c.customer_id 
          when i.customer_id1 then 1
          when i.customer_id2 then 2
          when i.customer_id3 then 3
        end
    ) as rn
  from customer c
  join invoice i on c.customer_id in (i.customer_id1, i.customer_id2, i.customer_id3)
)
where rn = 1;