如何联接3表并在子查询中执行并集?

时间:2019-06-13 15:08:27

标签: mysql sql

有四个表 Bill_entry 客户 Chit 现金。我想在以下查询中将表Customer与表Bill_entry联接在一起,它们具有公用列customer_id。目标是通过使用customer_id我也想在一个查询中打印customer_name

我已经尝试过,但是语法不正确

包含客户表之前的初始代码:

SELECT Bill_entry.*
FROM (SELECT * FROM Chit UNION SELECT * FROM Cash) as t1 RIGHT JOIN 
     entry
     ON (Bill_entry.bill_no = t1.bill_no)
WHERE t1.bill_no IS NULL

我尝试:

SELECT Bill_entry.*, Customer.customer_name
FROM ((SELECT * FROM Chit UNION SELECT * FROM Cash) as t1 RIGHT JOIN entry ON (Bill_entry.bill_no = t1.bill_no) WHERE t1.bill_no IS NULL)customer where Bill_entry.customer_id = Customer.Customer_id

1 个答案:

答案 0 :(得分:1)

只需添加另一个JOIN

SELECT e.*, cu.customer_name
FROM bill_entry e LEFT JOIN
     (SELECT * FROM Chit
      UNION ALL  -- assume you don't want to remove duplicates
      SELECT * FROM Cash
     ) c 
     entry e
     ON e.bill_no = c.bill_no LEFT JOIN
     Customer cu
     ON cu.customer_id = e.Customer_id
WHERE c.bill_no IS NULL;

请注意一些更改。

  • UNION-> UNION ALL。我假设您不想删除重复项,也不希望尝试删除重复项。
  • RIGHT JOIN-> LEFT JOIN。考虑LEFT JOIN通常通常要简单得多-将所有行保留在第一个表中,然后将其他行匹配。
  • JOIN条件全部包含在ON子句中,而不是WHERE子句中。