案例 1 - 在 where 子句中使用 OR 运算符的单个查询:
select * from users where name='smith' or nick='smith' (using index_merge )
Run Code Online (Sandbox Code Playgroud)
案例 2 - 在 where 子句中使用 equals 运算符的多个查询:
select * from users where name='smith'; (using single index);
select * from users where nick='smith'; (using single index);
Run Code Online (Sandbox Code Playgroud)
问:在案例 2 中是否有任何性能损失?
在这些情况下使用 UNION 是一种常见的优化(至少当您必须使用单个查询时):
select * from users where name='smith' /* using single index */
UNION
select * from users where nick='smith'; /* using single index */
Run Code Online (Sandbox Code Playgroud)
根据我的经验,我不喜欢依赖 index_merge (union),因为性能通常不如执行上述显式UNION技巧。
但每种情况可能会略有不同,因为性能可能取决于每个条件匹配的行数。
@jynus 在下面的评论中是正确的,该问题与为 UNION 创建的临时表有关。
我还想补充一点,很难为哪种类型的查询更快制定一般规则。这很大程度上取决于您查询的数据量、您使用的软件版本、您的操作系统和调优,以及每秒并发运行的查询数量。
回答此类问题的唯一可靠方法是在您的服务器上根据您的数据自行测试多个解决方案。
| 归档时间: |
|
| 查看次数: |
1814 次 |
| 最近记录: |