有四个表 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
答案 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
子句中。