[英]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.