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

标签 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

谢谢!

最佳答案

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

相关文章:

MYSQL JOIN SELECT 语句 - 省略重复项

sql - 在 1 个查询中获得问题和答案

sql - 如何从命令行测试 SQL 的有效性?

sql - 在 Teradata 中达到阈值后,将一列数字 session 化为 30 组

mysql - 返回 MySQL 中单个列中所有可能的值组合

c# - 通过PHP脚本隧道连接MySQL

Mysql - 具有多个接收 ID 的动态 UNION

mysql - SQL UNION ALL 消除重复项

MySQL - 获取过去一个月内最多 "liked"用户

java - mysql如何建立两个表之间的关系