Oracle/Mysql 查询指定表中记录总和

Oralce 查询语句:

SELECT SUM(X)
  FROM (SELECT COUNT( * )X
          FROM ALLTYPE_2
        UNION ALL
        SELECT COUNT( * )X
          FROM ALLTYPE_TAI
       )

Mysql 查询语句

SELECT (SELECT count(1) from db_data )+(SELECT count(1) from db_metadata) AS SumCount;

java 代码实现

public class ReadODPSTXT {
    public static String txt2String4Oracle(File file){
        StringBuilder result = new StringBuilder();
            String sql = "SELECT SUM(X)\n" +
                    "  FROM ( ";
            String exsql ="SELECT COUNT( * )X\n" +
                    "          FROM ";
            String unin =" UNION ALL ";
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次读一行
               sql=sql + exsql + s + unin;
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        sql = sql .substring(0,sql.lastIndexOf(unin))+");";
        return sql;
    }


    public static String txt2String4Mysql(File file){
        StringBuilder result = new StringBuilder();
        String sql = "SELECT ";
        String exsql ="(SELECT count(1) from ";
        String unin =" )+ ";
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次读一行
                sql=sql + exsql + s + unin;
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        sql = sql .substring(0,sql.lastIndexOf("+"))+" AS SumCount;";
        return sql;
    }
    public static void main(String[] args){
        File file = new File("D:/1.txt");
        System.out.println(txt2String4Oracle(file));
        System.out.println(txt2String4Mysql(file));
    }

你可能感兴趣的:(Oracle,mysql)