mysql - 左连接或条件执行缓慢

标签 mysql sql performance left-join

我有一个 SQL 查询,它在 or 条件下连接另一个表,如下所示:

select a.id,b.id from a left join b on (b.prop1=a.id or b.prop2=a.id)

1026 rows in set (12.77 sec)

如果我将查询分成两部分,没有或条件,它会快得多:

select a.id,b.id from a left join b on (b.prop1=a.id)
1026 rows in set (0.03 sec)

select a.id,b.id from a left join b on (b.prop2=a.id)
1026 rows in set (0.04 sec)

快得多,但我必须手动合并两个查询的结果。

为什么我的初始查询这么慢?我该怎么做才能让它更快?

我正在使用 mysql 5.5.35

最佳答案

尝试使用 UNION 代替 OR

select a.id,b.id from a left join b on (b.prop1=a.id)
UNION ALL
select a.id,b.id from a left join b on (b.prop2=a.id)

这应该比 OR

更快

关于mysql - 左连接或条件执行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27545167/

相关文章:

c++ - 网格 : "Sorting/Reordering" Arrays Referencing Shared Entries of Another for Cache Efficiency

php - 将一张表中的两列合并为一个输出

mysql - 当 N=0 时在 select 查询的限制子句中使用 N-1 时出现运行时错误

sql - 从 sql 查询查看数据到 vb.net

sql - 在 SQL View 中运行总计

mysql - 加快 MySQL 查询速度

php - 请帮助确定我的应用程序中的 MySQL 性能瓶颈

performance - 优化 Redis-Graph 查询性能(匹配)

javascript - 使用php和javascript加载连接到mysql的图表,无需刷新页面

c# - 根据MySQL数据库数据显示消息? C#