好的,我有四张桌子:
表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 wh_list_id
只有一个id字段,但没有rp_list_id
我想在结果表中有两个id,如下所示:
谢谢!
答案 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', ...
)。