【问题标题】:Retrieving Data from multiple tables from Database从数据库的多个表中检索数据
【发布时间】:2017-09-22 19:58:25
【问题描述】:

我在数据库中有一些表。他们有一些特定的模式。例如,假设我有表员工,然后是其他具有相同模式的表,例如:

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
    }
}

代码运行良好,但我如何一次从所有这些表中检索数据,而不是使用三个检查。如果这些表中的任何一个包含我想将其写入我的文件的数据。如何以更少的代码行高效地执行此操作?

如果有人能提出方法来检查这些表中的每一个是否包含数据,那就太好了,然后我可以调用我的代码将数据写入文件。

【问题讨论】:

    标签: java jdbc


    【解决方案1】:

    您可以在复杂查询中使用UNION 语句。请检查示例:

    SELECT id, name FROM employee WHERE id = ?
        UNION
    SELECT id, name FROM employee_x WHERE id = ?
        UNION
    ...
    

    您也可以使用UNION ALL 语句代替UNIONUNION 返回的唯一结果集没有重复的主要区别,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 "));
    

    【讨论】:

    • nops 首先我希望我的代码应该搜索它的数据库是否包含特定的表,如果包含则从中检索数据。这就是为什么我必须一次又一次地使用 if 语句
    • 在这种情况下,您可以从 db 中获取可用表,然后过滤所需并使用答案中定义的联合创建单个查询。
    • 这就是我要问的如何一次性过滤特定模式的表
    • 例如,如果你有db中所有表名的列表:List&lt;String&gt; tables,你可以生成sql查询:tables.stream().filter(predicate).map(t -&gt; "select * from " + t").collect(Collectors.joining(" UNION "))
    • 嘿,我没有得到你的代码..你能详细解释一下吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    相关资源
    最近更新 更多