簡體   English   中英

MYSQL 在左連接中添加 OR 子句會減慢查詢速度

[英]MYSQL adding OR clause in left join slowing up the query

我有兩個數據庫表: orderscustomers

我正在運行 SQL 以獲得 6 月份的所有訂單。

如果Ship ToBill To email 不同,我們將插入兩個不同的記錄,兩個電子郵件都發送給客戶表。

select o.order_id
     , o.total
     , c.customer_email 
  from orders o 
  left 
  join customers c
    ON o.bill_email = c.customer_email
    OR o.ship_email = c.customer_email
 where DATE(o.order_date) >= '2020-06-01'

但是由於這種情況,這個 SQL 加載時間過長,

ON o.bill_email=c.customer_email 
OR o.ship_email=c.customer_email

如何在 ON 子句中添加兩個條件?

任何幫助,將不勝感激。

使用兩個left join並將結果放在單獨的列而不是行中:

select o.order_id, o.total, cb.customer_email, so.customer_email
from orders o left join
     customers cb
     on o.bill_email = cb.customer_email left join
     customers cs
     o.ship_email = cs.customer_email
where o.order_date >= '2020-06-01';

請注意,不需要date() function。

也就是說,這似乎更容易表達為:

select o.order_id, o.total, o.bill_email
from orders o 
where o.order_date >= '2020-06-01'
union all
select o.order_id, o.total, o.ship_email
from orders o 
where o.order_date >= '2020-06-01' and s.ship_email <> o.bill_email;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM