0

我有两个数据库表:orderscustomers

我正在运行 SQL 来获取 6 月份的所有订单。

如果Ship ToBill To电子邮件不同,我们将插入两个不同的记录,这两个电子邮件都发送给客户表。

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 子句中添加两个条件?

任何帮助,将不胜感激。

4

1 回答 1

0

使用两个left joins 并将结果放在单独的列而不是行中:

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()功能不是必需的。

也就是说,这似乎更容易表达为:

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;
于 2020-06-19T14:56:11.627 回答