gpt4 book ai didi

sql - 如何联合 SELECT 两个具有两个表的 ID 的表?

转载 作者:可可西里 更新时间:2023-11-01 07:23:59 26 4
gpt4 key购买 nike

好的,我有四个表:

表 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

谢谢!

最佳答案

只需选择 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`

关于sql - 如何联合 SELECT 两个具有两个表的 ID 的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4241282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com