我有两个数据库表:orders和Customers。
我正在运行一个SQL来获取6月份的所有订单。
如果“收货人”和“收货人”电子邮件不同,我们将插入两个不同的记录,其中都包含“到客户的电子邮件”表。
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子句中同时添加这两个条件?
如有任何帮助,我们将不胜感激。
使用两个左联接
并将结果放在单独的列中,而不是行中:
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;