我想通过一个选择查询,通过两个表的日期列检索表行(表receipt
和invoice
)。
发票栏是:
| Bill_number | bill_date | amount_paid | total_amount | customer_id |
收据栏是:
| Bill_number | bill_date | total_amount | customer_id |
我可以一次从一个表中检索具有select
和join
子句的预期数据(特定日期),但我无法找到如何检索/搜索行中的特定日期一个查询中的两个表。
查询工作正常:
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
非常感谢。
答案 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')