postgresql 无法合并两个表中的数据

olhwl3o2  于 2023-02-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(205)

我有两个表,第一个表包含所有的记录,第二个表包含很少的记录,我试图把左连接得到第一个表的所有记录和第二个表中匹配的记录的数据列。

表A

id_step|id_workflow|id_action|
-------+-----------+---------+
      1|          1|       11|
      6|          1|       11|
      7|          1|       11|
      8|          1|       12|
      9|          1|       12|
     10|          1|       12|

表B

id_step|id_client|id_process|id_workflow|is_approved|action_by|action_date|
-------+---------+----------+-----------+-----------+---------+-----------+
      1|    10680|        10|          1|true       |         |           |

我希望获得以下结果预期输出

id_step|id_client|id_workflow|id_action|is_approved|action_by|action_date|
-------+---------+---------- +---------+-----------+---------+-----------+
      1|    10680|          1|       11|true       |         |           |
      6|    10680|          1|       11|pending    |         |           |
      7|    10680|          1|       11|pending    |         |           |
      8|    10680|          1|       11|pending    |         |           |
      9|    10680|          1|       11|pending    |         |           |
     10|    10680|          1|       11|pending    |         |           |

我试过查询

select 
x.id_step,
y.id_client,
x.id_workflow,
x.id_action, 
(case when y.is_approved is null then 'pending' else y.is_approved::text end ) as is_approved,
y.action_date,
y.action_by 
from nw_adsys_wfx_config as x 
left join nw_adsys_cli_wfx_process as y 
on x.id_step = y.id_step 
where x.id_workflow = 1
and y.id_process = 10

但我得到这个输出

id_step|id_client|id_workflow|id_action|is_approved|action_date|action_by|
-------+---------+-----------+---------+-----------+-----------+---------+
      1|    10680|          1|       11|true       |           |         |
cclgggtu

cclgggtu1#

查询包含左连接,但在两个表上还包含where条件,这违反了左连接的意图。
相反,您可以将条件移动到连接

...
from nw_adsys_wfx_config as x 
left join nw_adsys_cli_wfx_process as y 
  on x.id_step = y.id_step 
     AND y.id_process = 10
where x.id_workflow = 1

相关问题