2010-11-22 63 views
4

好的,我有四個表:如何結合使用兩個表的ID來選擇兩個表?

表1: 「f_withholdings」

alt text

表2: 「f_wh_list」

alt text

表3: 「f_rpayments」

alt text

表4: 「f_rp_list」

alt text

表1和表2通過wh_id字段 和表3和表4通過rp_id連接作爲圖像看到彼此連接。

我想工會選擇兩個表爲一體,是這樣的:

SELECT 
`wh_list_id`, 
`wh_name` AS `name`, 
`wh_list_date` AS `date`, 
`wh_list_amount` AS `amount`, 
`wh_list_pending` AS `pending`, 
`wh_list_comment` AS `comment` 
FROM 
`f_wh_list` LEFT JOIN `f_withholdings` ON `f_wh_list`.`wh_id` = `f_withholdings`.`wh_id` 

UNION ALL 

SELECT 
`rp_list_id`, 
`rp_name` AS `name`, 
`rp_list_date` AS `date`, 
`rp_list_amount` AS `amount`, 
`rp_list_pending` AS `pending`, 
`rp_list_comment` AS `comment` 
FROM `f_rp_list` LEFT JOIN `f_rpayments` ON `f_rp_list`.`rp_id` = `f_rpayments`.`rp_id` 

,我得到這個:

alt text

只有一個id字段從第一選擇wh_list_id的結果表,但沒有rp_list_id

我想在結果表中有兩個id,像belo w:

alt text

謝謝!

回答

6

只需選擇null作爲每個列中缺失的列。

SELECT 
`wh_list_id`, 
null AS `rp_list_id`, 
`wh_name` AS `name`, 
`wh_list_date` AS `date`, 
`wh_list_amount` AS `amount`, 
`wh_list_pending` AS `pending`, 
`wh_list_comment` AS `comment` 
FROM 
`f_wh_list` LEFT JOIN `f_withholdings` ON `f_wh_list`.`wh_id` = `f_withholdings`.`wh_id` 

UNION ALL 

SELECT 
null as `wh_list_id`, 
`rp_list_id`, 
`rp_name` AS `name`, 
`rp_list_date` AS `date`, 
`rp_list_amount` AS `amount`, 
`rp_list_pending` AS `pending`, 
`rp_list_comment` AS `comment` 
FROM `f_rp_list` LEFT JOIN `f_rpayments` ON `f_rp_list`.`rp_id` = `f_rpayments`.`rp_id` 
+1

+1:與Dmitri關於列別名相同的註釋 - 大多數數據庫不需要在UNION的第一個語句後定義的語句中顯式別名。 – 2010-11-22 00:47:50

1

相應的空欄只需添加到每個查詢(UNION的工作過的列位置,他們不在乎名稱或別名):

SELECT 
`wh_list_id`, 
NULL, 
... 

SELECT 
NULL, 
`rp_list_id`, 
... 

可能稍微好一點,保持並添加一個字段,指定該ID來自哪個查詢(例如,SELECT 'wh_list', ...)。

+0

+1:如果要引用列,別名很重要;)列引用由UNION的語句中的第一個定義。 – 2010-11-22 00:46:48

+0

只有當你想引用它的名字:)(這很公平,你應該) – Dmitri 2010-11-22 00:50:02