如何使用两个表的id联合选择(UNION SELECT)两个表?

4

好的,我有四个表:

表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语句中的一个id字段wh_list_id,但没有rp_list_id

我希望在结果表中同时拥有这两个id,类似下面这样:

alt text

谢谢!

2个回答

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的第一个语句之后定义的语句中不需要显式别名。 - OMG Ponies

1

只需对每个查询添加一个相应的空列(UNION按列位置工作,不关心名称或别名):

SELECT
`wh_list_id`,
NULL,
...

SELECT
NULL,
`rp_list_id`,
...

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


+1:如果你想引用一列,别名很重要;)列引用是由 UNION 语句中第一个定义的确定的。 - OMG Ponies
只有在你想要通过名称引用它时才需要这样做 :)(公平地说,你应该这样做) - Dmitri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接