我是JOOQ的菜鸟,需要帮助才能将SQL翻译成JOOQ。 所以我在这里有一个很长的SQL语句:
请参阅此图片以获得更好的洞察力:Outer Join
SELECT SUM(DECODE(VVS.VVS_ZWS_ID, 47, DECK.DEC_BRUTTOPRAEMIE_100, DECK.DEC_BRUTTOPRAEMIE_FOLGE))
FROM deck, agd, vvs, agv
WHERE vvs.vvs_ver_nummer = verNummer
AND vvs.vvs_nummer = vvsNummer
AND agv.agv_code = vvs.vvs_agv_code
AND deck.dec_ver_nummer = vvs.vvs_ver_nummer
AND deck.dec_vvs_nummer = vvs.vvs_nummer
AND deck.dec_tbl_code = 'KH'
AND agd.agd_code(+) = deck.dec_agd_code
AND ( NVL(agv.agv_aenderungstyp, 'NULL') IN ('4', '5')
OR NVL(agd.agd_aenderungstyp, 'NULL') NOT IN ('4', '5');
我用这个翻译了SQL语句:
create.select(sum(decode().when(vvs.VVS_ZWS_ID.eq(47),deck.DEC_BRUTTOPRAEMIE_100)
.otherwise(deck.DEC_BRUTTOPRAEMIE_FOLGE)))
.from(deck, vvs, agv)
.rightOuterJoin(agd)
.on(agd.AGD_CODE.eq(deck.DEC_AGD_CODE))
.where(vvs.VVS_VER_NUMMER.eq(verNummer))
.and(vvs.VVS_NUMMER.eq(vvsNummer))
.and(agv.AGV_CODE.eq(vvs.VVS_AGV_CODE))
.and(deck.DEC_VER_NUMMER.eq(vvs.VVS_VER_NUMMER))
.and(deck.DEC_VVS_NUMMER.eq(vvs.VVS_NUMMER))
.and(deck.DEC_TBL_CODE.eq("KH"))
.and(nvl(agv.AGV_AENDERUNGSTYP, "NULL")
.in("4", "5")
.or(nvl(agd.AGD_AENDERUNGSTYP, "NULL")
.notIn("4", "5")))
.fetch();
我的问题是:
1.在SQL语句from
中,我有四个表,分别是deck
,agd
,vvs
和agv
。
agd
表必须与deck
上的agd.agd_code(+) = deck.dec_agd_code
表结合使用。我是否正确翻译了sql?
2.我应该如何处理vvs
和agv
,因为这些表位于agd
的{{1}}之后?
我花了两天时间考虑这个问题而且我无法解决这个问题。
谢谢!
答案 0 :(得分:1)
虽然我通常不建议使用弃用的Oracle样式的外连接语法,但请注意jOOQ确实通过Field.plus()
支持它,所以你可以写:
<强> SQL 强>
AND agd.agd_code(+) = deck.dec_agd_code
<强> jOOQ 强>
.and(agd.AGD_CODE.plus().eq(deck.DEC_AGD_CODE))
除此之外,问题解释起来更简单。您将“经典”表列表(FROM
子句中的几个表)与ANSI连接混合在一起,这总是令人困惑。使用jOOQ执行此操作时,jOOQ会将ANSI连接表达式附加到表列表的最后一个表中。在您的情况下,这导致了以下FROM
子句:
-- Parentheses added for illustration purposes
FROM deck, vvs, (agv RIGHT OUTER JOIN agd ON agd.AGD_CODE = deck.DEC_AGD_CODE)
在这种情况下,您可能需要LEFT OUTER JOIN
,如果您的查询可能正确。
但它仍然会令人困惑,所以无论如何,我强烈建议您先将查询迁移到所有ANSI连接:
<强> SQL 强>
SELECT SUM(DECODE(VVS.VVS_ZWS_ID,
47, DECK.DEC_BRUTTOPRAEMIE_100,
DECK.DEC_BRUTTOPRAEMIE_FOLGE))
FROM deck
JOIN vvs
ON deck.dec_ver_nummer = vvs.vvs_ver_nummer
AND deck.dec_vvs_nummer = vvs.vvs_nummer
JOIN agv
ON agv.agv_code = vvs.vvs_agv_code
LEFT JOIN agd
ON deck.dec_agd_code = agd.agd_code
WHERE vvs.vvs_ver_nummer = verNummer
AND vvs.vvs_nummer = vvsNummer
AND deck.dec_tbl_code = 'KH'
AND ( NVL(agv.agv_aenderungstyp, 'NULL') IN ('4', '5')
OR NVL(agd.agd_aenderungstyp, 'NULL') NOT IN ('4', '5'));
<强> jOOQ 强>
create.select(sum(decode().when(vvs.VVS_ZWS_ID.eq(47),deck.DEC_BRUTTOPRAEMIE_100)
.otherwise(deck.DEC_BRUTTOPRAEMIE_FOLGE)))
.from(deck)
.join(vvs)
.on(deck.DEC_VER_NUMMER.eq(vvs.VVS_VER_NUMMER))
.and(deck.DEC_VVS_NUMMER.eq(vvs.VVS_NUMMER))
.join(agv)
.on(agv.AGV_CODE.eq(vvs.VVS_AGV_CODE))
.leftOuterJoin(agd)
.on(agd.AGD_CODE.eq(deck.DEC_AGD_CODE))
.where(vvs.VVS_VER_NUMMER.eq(verNummer))
.and(vvs.VVS_NUMMER.eq(vvsNummer))
.and(deck.DEC_TBL_CODE.eq("KH"))
.and(nvl(agv.AGV_AENDERUNGSTYP, "NULL")
.in("4", "5")
.or(nvl(agd.AGD_AENDERUNGSTYP, "NULL")
.notIn("4", "5")))
.fetch();