如何将两个表与两个表的ID联合起来?

Dav*_*eel 4 mysql sql union union-all

好的,我有四张桌子:

表1:"f_withholdings"

替代文字

表2:"f_wh_list"

替代文字

表3:"f_rpayments"

替代文字

表4:"f_rp_list"

替代文字

表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`
Run Code Online (Sandbox Code Playgroud)

我明白了

替代文字

wh_list_id结果表中第一个SELECT只有一个id字段,但没有rp_list_id

我想在结果表中有两个id,如下所示:

替代文字

谢谢!

tva*_*son 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`
Run Code Online (Sandbox Code Playgroud)