jOOQ - how to use .whereNotExists() with condition

2019-07-23 03:15发布

I have a following jOOQ query, originally composed with the help of Lukas Eder in this question.

create.insertInto(DATA,DATA.TICKER,DATA.OPEN,DATA.HIGH,DATA.LOW,DATA.CLOSE,DATA.DATE)
.select(
    select(
        val(dailyData.getTicker()),
        val(dailyData.getOpen()),
        val(dailyData.getHigh()),
        val(dailyData.getLow()),
        val(dailyData.getClose()),
        val(dailyData.getDate())
        )
    .whereNotExists(
        selectOne()
        .from(DATA)
        .where(DATA.DATE.eq(dailyData.getDate()))
    )
).execute();

This query works properly. In addition, I would like to modify to accomplish the following feat, but I am not certain it is actually doable. In simple english:

"Insert the row if a row with the same 'date' column doesn't already exist in the table. If it exists AND 'realtime close' column is true, update the 'close', otherwise do nothing."

The first part is already covered by the existing query, but the second part with if...update... is not and that's what I need help with.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-23 03:52

In plain PostgreSQL, you would write this query as follows:

INSERT INTO data (ticker, open, high, low, close, date)
VALUES (:ticker, :open, :high, :low, :close, :date)
ON CONFLICT (date)
DO UPDATE SET close = false WHERE close

This translates to the following jOOQ query:

DSL.using(configuration)
   .insertInto(DATA)
   .columns(
       DATA.TICKER, 
       DATA.OPEN,
       DATA.HIGH,
       DATA.LOW,
       DATA.CLOSE,
       DATA.DATE)
   .values(
       dailyData.getTicker(),
       dailyData.getOpen(),
       dailyData.getHigh(),
       dailyData.getLow(),
       dailyData.getClose(),
       dailyData.getDate())
   .onConflict()
   .doUpdate()
   .set(DATA.CLOSE, inline(false))
   .where(DATA.CLOSE)
   .execute();
查看更多
登录 后发表回答