4

好的,我有四张桌子:

表 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`

我明白了:

替代文字

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

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

替代文字

谢谢!

4

2 回答 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`
于 2010-11-22T00:34:13.397 回答
1

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

SELECT
`wh_list_id`,
NULL,
...

SELECT
NULL,
`rp_list_id`,
...

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

于 2010-11-22T00:34:54.357 回答