如何用一个查询获得两个select join语句的结果

时间:2016-06-28 20:59:15

标签: mysql join

我想通过一个选择查询,通过两个表的日期列检索表行(表receiptinvoice)。

发票栏是:

| Bill_number | bill_date | amount_paid | total_amount | customer_id | 

收据栏是:

| Bill_number | bill_date | total_amount | customer_id |

我可以一次从一个表中检索具有selectjoin子句的预期数据(特定日期),但我无法找到如何检索/搜索行中的特定日期一个查询中的两个表。

查询工作正常:

SELECT receipt.*, customer.customer_name
FROM receipt
INNER JOIN customer ON receipt.customer_id = customer.customer_id
WHERE receipt.bill_date = '2016-06-24'  

SELECT invoice.*, customer.customer_name
FROM invoice
INNER JOIN customer ON invoice.customer_id = customer.customer_id
WHERE invoice.bill_date = '2016-06-24'

预期结果:

|bill_number| bill_date |amount_paid| total_amount |customer_id| customer_name |
       1     2016-06-24      20          20             1            John     <-- invoice table
       1     2016-06-24                  20             1            John     <-- receipt table

非常感谢。

1 个答案:

答案 0 :(得分:0)

您只需使用UNION即可。如果两个表不完全匹配,则可能必须定义缺少的列(例如,在这种情况下为amount_paid列):

(SELECT bill_number, bill_date, amount_paid, total_amount, customer.customer_id, customer_name
 FROM receipt
 INNER JOIN customer ON receipt.customer_id = customer.customer_id
 WHERE receipt.bill_date = '2016-06-24')
UNION
(SELECT bill_number, bill_date, NULL AS amount_paid, total_amount, customer.customer_id, customer_name
 FROM invoice
 INNER JOIN customer ON invoice.customer_id = customer.customer_id
 WHERE invoice.bill_date = '2016-06-24')

这是link to the MySQL documentation