我有三张桌子。
客户 - 姓名,电子邮件
历史记录 - id,customer_id,attendee_id,date
与会者 - 姓名,电子邮件
我正在尝试使用历史记录表来获取名称和电子邮件,如果customer_id为-1,那么需要从客户表中的参与者表中获取名称和电子邮件,如下所示:
SELECT * FROM history
left JOIN attendee ON attendee.id = history.attendee_id AND history.customer_id= '-1'
left JOIN customer ON customer.id = history.customer_id AND history.customer_id != '-1'
WHERE history.id = '605';
我可以使用union来做同样的事情但不使用join
联合所有代码如下
select cus.name,cus.email from histroy
join customer cus on cus.id = history.customer_id and history.customer_id not in ('0','-1')
union all
select cus.name,cus.email from history
join attendee cus on cus.id = history.attendee_id and history.attendee_id not in ('0','-1')
我可以使用join编写上面的代码。