【问题标题】:Using query with "IN clause" vs "="使用带有“IN 子句”和“=”的查询
【发布时间】:2021-02-19 05:20:20
【问题描述】:

需要建议,因为由于性能改进,我需要将所有循环查询转换为 IN 子句。 我有以下可能因迭代而异的条件..

Where recordID=2323 and (origin=626 or destination=319);
Where recordID=2323 and (origin=319 or destination=789);
Where recordID=2323 and (origin=567 or destination=989);
Where recordID=2323 and (origin=767 or destination=626);

为了提高性能,我想像这样将这些查询转换为 IN 子句..

  Where recordID=2323 and (origin IN(626,319,567,767) or destination IN (319, 789, 989, 626));

我的问题是两种方法的结果计数是否相同? 有没有其他方法或任何其他方式来做到这一点。

问题是我的最终计数与每种方法相比并不相似。

【问题讨论】:

    标签: mysql sql select in-clause


    【解决方案1】:

    不幸的是,没有很好的方法来优化在不同列上使用or 条件的查询。如果查询简单,可以使用union all

    select t.*
    from t
    where recordID = 2323 and origin = 626
    union all
    select t.*
    from t
    where recordID = 2323 and destination = 319 and origin <> 626;
    

    这个版本的查询可以使用两个索引:

    • (recordID, origin)
    • (recordID, destination, origin)

    编辑:

    如果您不关心性能,那么您使用 in 的方法就可以了——并且等同于您的原始逻辑。

    【讨论】:

    • 感谢 Gordon 的快速响应,Union all 都可以解决问题,但我的 java 程序迭代每次都会更改起点/终点,最终我会多次执行。就像上次迭代是 1000 次一样。
    猜你喜欢
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多