2016-06-28 11 views
0

1つの選択クエリで両方のテーブルのテーブル列(テーブルのreceiptinvoice)のテーブル行を取得したいとします。1つのクエリで2つのSELECT結合ステートメントの結果を取得する方法

| Bill_number | bill_date | amount_paid | total_amount | customer_id | 

レシートの列は次のとおりです:私は、一度に1つのテーブルからselectjoin句と期待されるデータ(特定の日付)を取得することができ

| Bill_number | bill_date | total_amount | customer_id | 

、私

請求書の列がある

1つのクエリで両方のテーブルの特定の日付を検索/検索する方法を見つけることができませんでした。

クエリが個別に正常に動作:

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

データセットのない別の結果セット。私たちは霊的ですか? – Strawberry

答えて

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です。

+0

ありがとう、しかし、私はどのように私はそれらのすべての列が必要なユニオンと異なる数の列を取得できます。 –

+0

@ JalilAzizian私の答えは – julienc

+0

で、一致しない列や欠落した列については、IF(bill_number!= 0,0、0)としてamount_paidを使用して、その列を仮想的に作成できます。 –

関連する問題