我在数据库中有以下SCORE表:
id | val1 | val2 | val3 | val4 |
1 40 100 80 90
2 90 70 90 45
3 50 60 100 30
4 20 30 30 40
我想从列val1,val2和val3中选择最小值,并使用以下代码将其存储在变量中:
int maxVal = 0;
Statement s2 = conn.createStatement();
s2.execute("SELECT min(val1,val2,val3) FROM SCORE");
ResultSet rs1 = s2.getResultSet(); //
while ( rs1.next() ){
maxVal = rs1.getDouble(1);
}
并收到错误消息。有没有一种简单的方法可以从表中的多个列中获取最小值?
答案 0 :(得分:2)
如果您使用的是Java 8,则可以从Java代码中获取min:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT min(val1), min(val2), min(val3) FROM SCORE");
if (rs.next()) {
minValue = DoubleStream.of(
rs.getDouble(1), rs.getDouble(2), rs.getDouble(3)
).min().getAsDouble();
}
如果您使用的是Java 8以下,则可以使用:
if (rs.next()) {
minValue = Math.min(Math.min(rs.getDouble(1), rs.getDouble(2)), rs.getDouble(3));
}
答案 1 :(得分:2)
我想出了
SELECT MIN(val)
FROM (SELECT MIN(val1) AS val FROM SCORE
UNION SELECT MIN(val2) FROM SCORE
UNION SELECT MIN(val3) FROM SCORE)