java - 使用 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 来解决这个问题呢?
解决方案
您可以在类似于 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;
推荐阅读
- r - 交叉验证帮助:模型中的错误。
- r - R:组合两组数字
- javascript - 通过 map 对多个元素反应 refs
- postgresql - Heroku 无法与 Postgres DB/Knex/Express 连接
- java - 我的代码会编译,但是当我运行它时,它有一个错误。为什么?
- javascript - 递增 1,然后 10,然后 100?
- typescript - 如何将函数添加到命名空间
- c# - 如何引用 2 个具有相同名称的不同 DLL?
- java - 为什么使用 PrintWriter 发送字符串后 JAVA BufferedReader 无法从 python 客户端接收字符串?
- javascript - Swagger UI 3.19.4(Swagger 2.0)查询参数选择