我有三个查询,我想将其合并到一个查询中,该查询可以接受WHERE
个可变长度的参数;我不记得我的生活如何做到这一点。
PreparedStatement queryOne = connection.prepareStatement
("SELECT columnOne, columnTwo, columnThree FROM tableOne WHERE columnOne = ?;" );
PreparedStatement queryTwo = connection.prepareStatement
("SELECT columnOne, columnTwo, columnThree FROM tableOne WHERE columnTwo = ?;" );
PreparedStatement queryThree = connection.prepareStatement
("SELECT columnOne, columnTwo, columnThree FROM tableOne WHERE columnOne = ? AND columnTwo = ?;" );
答案 0 :(得分:1)
所有三个查询都从同一个表中选择相同的列,因此可以在一个语句中轻松完成它们的联合:
SELECT columnOne, columnTwo, columnThree
FROM tableOne
WHERE columnOne = ?
or columnTwo = ?
or (columnOne = ? AND columnTwo = ?)
答案 1 :(得分:0)
回答了我自己的问题,请随时了解这是否是不好的做法。
String columnOne = getValue();
String columnTwo = getValue();
String queryString = "SELECT columnOne, columnTwo, columnThree FROM tableOne"
if (columnOne != null && columnTwo != null)
queryString = queryString + "WHERE columnOne = ? AND columnTwo = ?"
else if (columnOne != null)
queryString = queryString + "WHERE columnOne = ?"
else if (columnTwo != null)
queryString = queryString + "WHERE columnTwo = ?"
PreparedStatement query = connection.prepareStatement(queryString);