【问题标题】:Join statement with different conditions on different row set不同行集上不同条件的join语句
【发布时间】:2013-08-21 08:21:27
【问题描述】:

我需要在不同的行集上使用不同的条件连接两个表。

例如RowID < 100 on t1.ColA = t2.ColBRowID >= 100 on t1.ColA = t2.ColB+1

我实现如下:

... On (RowID <100 and t1.ColA=t2.ColB) OR (RowID >=100 on t1.ColA=t2.ColB+1) ...

但它非常非常慢,那么问题是什么,有什么更好的解决方案?

【问题讨论】:

    标签: sql sql-server tsql join


    【解决方案1】:
    RowID <100 on t1.ColA=t2.ColB 
    
    UNION ALL
    
    If RowID >=100 on t1.ColA=t2.ColB+1
    

    试试这个解决方案。

    【讨论】:

    • +1 由于 OR 语句会破坏他的索引,因此该解决方案应该快速添加它。
    • 非常好。 200000条记录1s,但是我的查询问题是什么?!
    【解决方案2】:

    你可以试试这个:

    On t1.ColA=CASE
    WHEN RowID<100 THEN t2.ColB
    WHEN RowID>=100 THEN t2.ColB+1
    END
    

    SELECT
    ...
    CASE
        WHEN RowID<100 THEN t2.Column
        WHEN RowID>=100 THEN t3.Column
    END
    ...
    Join t2 On t1.ColA=t2.ColB
    Join t2 as t3 On t1.ColA=t3.ColB+1
    

    可能会更快

    【讨论】:

    • 好的,两个单独的 equi 连接而不是一个非 equi 连接怎么样?你试过了吗?
    猜你喜欢
    • 1970-01-01
    • 2016-12-05
    • 2012-05-03
    • 2018-12-11
    • 2020-06-02
    • 1970-01-01
    • 2012-05-03
    • 2014-06-07
    • 2019-12-15
    相关资源
    最近更新 更多