SQL - 使用 OR 运算符进行左连接 (MySQL) [英] SQL - left join with OR operator (MySQL)

查看:87
本文介绍了SQL - 使用 OR 运算符进行左连接 (MySQL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 MySQL 数据库的左连接...

I have a left join on a MySQL database like this...

select  *
from tableA 
left join tableB on (tableA.id=tableB.id1 and tableB.col2='Red')

...它在 tableA 和 tableB 上的 >500K 行上执行正常

但是,将其更改为此(并假设索引没问题)...

However, changing it to this (and assuming indexes are OK)...

select  *
from tableA 
left join tableB on 
((tableA.id=tableB.id1 and tableB.col2='Red') OR
 (tableA.id=tableB.id2 and tableB.col2='Blue') )

...杀死它,在性能方面.

...kills it, in terms of performance.

那么为什么性能会下降?我可以换一种方式吗?

So why the performance hit? Can I do it another way?

推荐答案

EDIT

不确定你需要什么

  • 你能展示一些预期的结果吗
  • 您能告诉我们在性能方面杀死它"是什么意思(执行时间是否达到 20 秒?)

我不认为它更有效,但可以尝试一下.

I don't believe its more efficient but try it.

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...

您可以比较性能并将索引放在适当的列上(取决于您在全表和查询中的内容,但这里应该是 id、id1 和 col2)

You can compare the performance and put indexes on appropriated columns (depends on what you have in full table and query but here it should be id, id1 and col2)

这篇关于SQL - 使用 OR 运算符进行左连接 (MySQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆