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

时间:2010-11-22 00:27:38

标签: sql mysql union union-all

好的,我有四张桌子:

表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

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

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

alt text

谢谢!

2 个答案:

答案 0 :(得分: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)

只需为每个查询添加一个相应的空列(UNIONs在列位置之外工作,它们不关心名称或别名):

SELECT
`wh_list_id`,
NULL,
...

SELECT
NULL,
`rp_list_id`,
...

将ID保存在一列中可能稍微好一些,并添加一个字段来指定id来自哪个查询(例如SELECT 'wh_list', ...)。