我在数据库中有一些表。他们有一些特殊的模式。例如,考虑我有表employee,然后有其他具有相同模式的表,例如:
table 1:employee
table 2:employee_X
table 3:employee_Y
我想检查这些表是否包含数据,如果包含,那么我必须为每个表调用一些方法。我正在使用以下代码进行检索。
DatabaseMetaData meta = con.getMetaData();
ResultSet res = meta.getTables(null, null, "My_Table_Name", new String[] {"TABLE"});
while (res.next()) {
if(rs.getStrin(3).equals(employee)){
//my code to write data of this table to a file
}
if(rs.getString(3).equals(employee_X)){
//my code to write data to the same file
}
if(rs.getString(3).equals(employee_Y)){
//code to write data to the same file from this table
}
}
代码工作正常,但是我如何一次从所有这些表中检索数据,而不是使用三个检查。如果这些表中的任何一个包含数据,我想将其写入我的文件。如何以更少的代码行有效地执行此操作?
如果有人可以建议在单个语句中检查这些表中的每个表是否包含数据,然后再调用代码将数据写入文件的方法,那将是很好的。
最佳答案
您可以在复杂的查询中使用UNION
语句。请检查示例:
SELECT id, name FROM employee WHERE id = ?
UNION
SELECT id, name FROM employee_x WHERE id = ?
UNION
...
您也可以使用
UNION ALL
语句代替UNION
。 UNION
返回唯一结果集而不重复的主要区别,UNION ALL
允许重复。请检查此链接https://www.w3schools.com/sql/sql_union.asp以获取有关union
语句的详细说明。如果您需要使用自定义过滤表创建
UNION
查询,请检查示例:Set<String> requiredTables = new HashSet<>();
// fill set with required tables for result query
requiredTables.add("employee");
ResultSet res = meta.getTables(null, null, "My_Table_Name",
new String[] {"TABLE"});
List<String> existentTables = new LinkedList<>();
while(res.next()) {
if (requiredTables.contains(res.getString(3)) {
existentTables.add(res.getString(3));
}
}
String query = existentTables.stream().map(table -> String.format("SELECT * FROM %s", table)).collect(Collectors.joinning(" UNION "));