How to union SELECT two tables with ids of both tables?

Daveel picture Daveel · Nov 22, 2010 · Viewed 10.3k times · Source

Ok, I have four tables:

Table 1: "f_withholdings"

alt text

Table 2: "f_wh_list"

alt text

Table 3: "f_rpayments"

alt text

Table 4: "f_rp_list"

alt text

Table 1 and Table 2 are connected with each other by wh_id field and Table 3 and Table 4 are connected by rp_id as seen in picture.

I want to union select both tables into one, something like:

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`

and I get this:

alt text

there is only one id field from first SELECT wh_list_id in result table, but no rp_list_id

I'd like to have both ids in result table, something like below:

alt text

Thanks!

Answer

tvanfosson picture tvanfosson · Nov 22, 2010

Just select null as the column that is missing from each.

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`