SQL 如何实现多表并行取数
一些 SQL 查询场景下可以通过多线程并行执行多条 SQL 进行取数,以利于多 CPU 优势,加快获取表数据的速度。
下面用多线程获取SCORES成绩表、STUDENTS学生表的数据后,通过 SCORES 的 STUDENTID 与学生记录进行关联操作。
SCORES | |||
CLASS | STUDENTID | SUBJECT | SCORE |
Class one | 1 | English | 84 |
Class one | 1 | Math | 77 |
Class one | 1 | PE | 69 |
Class one | 2 | English | 81 |
Class one | 2 | Math | 80 |
... | ... |
STUDENTS | |||
ID | NAME | GENDER | AGE |
1 | Emily | F | 17 |
2 | Elizabeth | F | 16 |
3 | Sean | M | 17 |
4 | Lauren | F | 15 |
5 | Michael | M | 16 |
... | ... |
1. 集算器编写脚本demo.dfx:
A | B | C | |
1 | select * from SCORES | select * from STUDENTS | / 查询成绩表、学生表的 SQL |
2 | fork [A1:B1] | / 以 SQL 为参数启动多线程 | |
3 | =connect("hsql") | / 连接数据库 | |
4 | =B3.query@x(A2) | / 每个线程执行 SQL 查询数据将结果返回到 A2 格 | |
5 | >SCORES=A2(1) | >STUDENTS=A2(2) | / 获取查询结果 |
6 | =SCORES.switch@i(STUDENTID, STUDENTS:ID) | / 将 SCORES 中的 STUDENTID 字段值转化为对应的学生记录 | |
7 | =A6.new(CLASS, STUDENTS.NAME, STUDENTS. AGE, STUDENTS.GENDER, SUBJECT, SCORE) | / 提取学生成绩数据组成序表 |
A6 | CLASS | STUDENTID | SUBJECT | SCORE |
Class one | [1,Emily,F ,17] | English | 84 | |
Class one | [1,Emily,F ,17] | Math | 77 | |
Class one | [1,Emily,F ,17] | PE | 69 | |
Class one | [2, Elizabeth,F,16] | English | 81 | |
Class one | [2, Elizabeth,F,16] | Math | 80 | |
... | ... |
A7 | CLASS | NAME | AGE | GENDER | SUBJECT | SCORE |
Class one | Michael | 16 | M | English | 72 | |
Class one | Michael | 16 | M | Math | 60 | |
Class one | Michael | 16 | M | PE | 91 | |
Class one | John | 13 | M | English | 90 | |
Class one | John | 13 | M | Math | 69 | |
... | ... |
public static void doWork() {
Connection con = null;
java.sql.Statement st;
try{
Class.forName("com.esproc.jdbc.InternalDriver");
con = DriverManager.getConnection("jdbc:esproc:local://");
// 调用脚本 demo.dfx
st=con.createStatement();
ResultSet rst = st.executeQuery("call demo");
System.out.println(rst);
} catch(Exception e){
System.out.println(e);
} finally{
// 关闭连接
if (con!= null) {
try {
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
}