我在 MySQL 数据库上有一个像这样的左连接...
select *
from tableA
left join tableB on (tableA.id=tableB.id1 and tableB.col2='Red')
...在 tableA 和 tableB 上执行 >500K 行
但是,将其更改为此(并假设索引正常)...
select *
from tableA
left join tableB on
((tableA.id=tableB.id1 and tableB.col2='Red') OR
(tableA.id=tableB.id2 and tableB.col2='Blue') )
...在性能方面将其杀死。
那么为什么性能会受到影响?我可以换一种方式吗?
最佳答案
编辑
不太确定你需要什么
- 你能展示一些预期的结果吗
- 你能告诉我们你所说的“在性能方面杀死它”是什么意思吗(执行时间是否达到 20 秒?)
我不相信它更有效率,但试试吧。
select
*
from
tableA as a
left join tableB as b1
on a.id=b1.id1
and b1.col2='Red'
left join tableB as b2
on a.id=b2.id2
and b2.col2='Blue'
where
(b1.id1 is not null or b2.id2 is not null)
or (b1.id1 is null and b2.id2 is null)
您必须使用 CASE WHEN
...管理 SELECT
中的结果...
您可以比较性能并将索引放在适当的列上(取决于您在全表和查询中的内容,但这里应该是 id、id1 和 col2
)
关于mysql - SQL - 使用 OR 运算符左连接 (MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22926885/