具有单个匹配条件的sql查询中的OR子句

时间:2017-09-18 08:34:15

标签: sql oracle

我可以在oracle中使用单个输入条件的OR claue,如下面的代码段(?是单个输入参数):

Select t1.name, t1.value from table t1 where t1.name ='abc' and (t1.col OR 
t1.value =? );

3 个答案:

答案 0 :(得分:1)

您可以使用IN子句:

Select t1.name, t1.value 
from table t1 
where t1.name = 'abc' 
  and ? in (t1.col, t1.value);

答案 1 :(得分:1)

有几种方法可以做到:

使用IN子句:

SELECT name, value
FROM   table
WHERE  name ='abc'
AND    ? IN ( col, value );

或使用子查询:

SELECT name, value
FROM   table t
       INNER JOIN
       ( SELECT ? AS input_var FROM DUAL ) v
       ON ( t.col = v.input_var OR t.value = v.input_var )
WHERE  name ='abc';

答案 2 :(得分:0)

如果要在Java代码中重用查询中的值,可以考虑使用预准备语句:

String sql = "select t1.name, t1.value from table t1 where t1.name =? and (t1.col = ? or t1.value = ?)";
int someVal = 10;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString("abc");
ps.setInt(2, someVal);
ps.setInt(3, someVal);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    String name = rs.getString("name");
    String value = rs.getString("value");
}

如果直接从Oracle尝试类似的事情,您可以使用会话变量:

declare
    some_val number := 10;
begin
    select t1.name, t1.value
    from table t1
    where t1.name ='abc' and (t1.col = some_val or t1.value = some_val);
end;
/