首页 > 解决方案 > 使用 JPA 合并两个相似的表

问题描述

我们有两个相似的表,有很多共同的列

表 AA

ID,名称,活动...

1,A,1

2,空,1

表BB

ID,名称,活动...

2,从_B,0

我需要获取 AA 表,但是只要 AA 表中有一个字段为空,但同时 BB 表中的字段不为空,我想从第二个表中重写该字段。对于上面的例子,我想得到这个结果

1,A,1

2,来自_B,1

我尝试过这样的事情

select * from AA left join BB on AA.id=BB.id

并且在这个查询中,而不是 * 选择表 AA 中出现的所有字段,并在为空的情况下将它们替换为 BB 中的相应字段,但是当公共字段的数量足够大时,这似乎不是一个好的解决方案。那么有没有什么好的方法可以通过使用 spring boot 和 JPA 来解决这个问题呢?

标签: javaspringspring-bootspring-data-jpajpa-2.0

解决方案


您可以在类似于 if 条件的查询中使用case 。在您的情况下,查询应该是这样的

select a.id, (case when(a.name is null and b.name is not null) then 
b.name else a.name end) as name, a.active from "tableA" as a
left join "tableB" b on a.id=b.id;

此外,您可以使用类似于案例的if-condition ,它应该是这样的。

SELECT col1, col2, IF( action = 2 AND state = 0, 1, 0 ) AS state from tbl1;

或者

SELECT col1, col2, (case when (action = 2 and state = 0) then 1 else 0 end) as state from tbl1;

推荐阅读