簡體   English   中英

jOOQ-如何使用具有多個條件的WHERE創建SQL查詢

[英]jOOQ - How to create a SQL query with WHERE having multiple conditions

我想創建一個查詢,它應該像這樣工作:

SELECT 
  sensor_id,
  measurement_time,
  measurement_value
FROM 
  public.measurement_pm2_5
WHERE
  (sensor_id = 1 AND measurement_time BETWEEN to_timestamp(123) AND to_timestamp(100000))
  OR (sensor_id = 1 AND measurement_time BETWEEN to_timestamp(500000) AND to_timestamp(99999999999))
  OR (sensor_id = 49 AND measurement_time BETWEEN to_timestamp(555) AND to_timestamp(556))
  OR (sensor_id = 9 AND measurement_time BETWEEN to_timestamp(7654) AND to_timestamp(999999299347))
  OR (sensor_id = 44 AND measurement_time BETWEEN to_timestamp(4252) AND to_timestamp(999949999348))
  OR (sensor_id = 60 AND measurement_time BETWEEN to_timestamp(63452) AND to_timestamp(999998999349))
  ;

此查詢中OR的數量可能有所不同。

甚至可以使用具有類型安全API的jOOQ來構建這樣的查詢,還是必須使用純SQL手動創建它?

我知道,如果沒有關於measurement_time其他聲明(每個sensor_id都不同),它將看起來像這樣:

Set<Integer> sensorIds = new HashSet<>();
sensorIds.add(1);
sensorIds.add(49);
sensorIds.add(9);
sensorIds.add(44);
sensorIds.add(60);
Timestamp startTime = new Timestamp(123L);
Timestamp endTime = new Timestamp(999999999999L);
try(java.sql.Connection conn = Connection.hikariDataSource.getConnection()) {
    System.out.println("SQL = " + DSL.using(conn).select()
        .from(MEASUREMENT_PM2_5)
        .where(MEASUREMENT_PM2_5.SENSOR_ID.in(sensorIds))
        .and(MEASUREMENT_PM2_5.MEASUREMENT_TIME.between(startTime, endTime))
        .getSQL());
} catch (SQLException e) {
    e.printStackTrace();
}

但是不幸的是,對於不同的sensor_id我有不同的時間戳。

private class TimeRange {
    Timestamp startTime;
    Timestamp endTime;

    Timestamp getStartTime() {
        return startTime;
    }

    Timestamp getEndTime() {
        return endTime;
    }
}
...
Map<Integer, List<TimeRange>> sensorIDsWithTimeRange

JooQ完全可以做到。

您要創建一個合適的Condition並將其插入查詢中。

問題是如何建立條件...建立條件的方法有很多。

例如:

final Condition c1 = someField.eq(someOtherField);
// or
final Condition c1 = someField.lessThan(someValue);

獲取Field參考的方式取決於您的設置。

可能性無窮無盡。 然后如果您有兩個條件c1和c2,要建立條件c,則可以:

final Condition c = c1.and(c2); // or c1.or(c2)

並將條件c插入您的最終查詢中。

如果您使用JooQ,則很可能已經生成了元數據代碼,如果沒有,即使僅使用JDBC URL,JooQ也可以為您推斷表名和列名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM