MySQL三表联查的例子

MySQL三表联查的例子_第1张图片

1、查询每个账户的折人民币余额,返回:账户代号、账户名称、币种、开户机构、账户状态、账户折人民币余额

 

1 String sql = "SELECT a.zhdh, a.zhmc, a.bz, a.khjg, a.zhzt, (b.zhye * c.hl) AS rmb_total "
2                     + "FROM t_zhye b LEFT JOIN t_ckzh a " 
3                     + "ON b.zhdh = a.zhdh LEFT JOIN t_hl c " 
4                     + "ON a.bz = c.bz";

 

 

 

 

2、查询账户余额(折人民币后)最大的账户信息,返回:账户代号、账户名称、币种、开户机构、账户余额

方法1(采用倒排序,然后选择第一个):

 

1 String sql = "SELECT a.zhdh, a.zhmc, a.bz, a.khjg, b.zhye, (b.zhye * c.hl) AS rmb_total "
2                     + "FROM t_zhye b LEFT JOIN t_ckzh a " 
3                     + "ON b.zhdh = a.zhdh LEFT JOIN t_hl c " 
4                     + "ON a.bz = c.bz "
5                     + "ORDER BY rmb_total desc LIMIT 1";

 

 

 

方法2:

1 String sql = "SELECT a.zhdh, a.zhmc, a.bz, a.khjg, b.zhye, (b.zhye * c.hl) AS rmb_total "
2                     + "FROM t_zhye b LEFT JOIN t_ckzh a " 
3                     + "ON b.zhdh = a.zhdh LEFT JOIN t_hl c " 
4                     + "ON a.bz = c.bz "
5                     + "WHERE (b.zhye * c.hl) = " 
6                     + "(SELECT MAX(e.zhye * f.hl) " 
7                     + "FROM t_zhye e LEFT JOIN t_ckzh d "
8                     + "ON e.zhdh = d.zhdh LEFT JOIN t_hl f " 
9                     + "ON d.bz = f.bz)";

 

3、查询开户账户数少于2个的机构相关信息,返回:开户机构、开户账户数、存款总余额(折人民币)

 

1 String sql = "SELECT * FROM "
2                     + "(SELECT a.khjg, COUNT(a.zhdh) AS total, SUM(b.zhye * c.hl) AS rmb_sum "
3                     + "FROM t_zhye b LEFT JOIN t_ckzh a " 
4                     + "ON b.zhdh = a.zhdh LEFT JOIN t_hl c " 
5                     + "ON a.bz = c.bz "
6                     + "GROUP BY a.khjg) pp "
7                     + "WHERE pp.total < 2";

 

 

4、假设账户状态=0,表示“账户正常”,账户状态=2表示“账户销户”,请查询不同机构下,账户不同状态的余额,返回:开户机构、正常账户余额之和、销户账户余额之和;

 

1 String sql = "SELECT a.khjg AS kh, a.zhzt, SUM(b.zhye) "
2                     + "FROM t_ckzh a LEFT JOIN t_zhye b "
3                     + "ON a.zhdh = b.zhdh "
4                     //要用两个分组的话,直接用逗号隔开就行了
5                     + "GROUP BY a.khjg, a.zhzt";

 

 

 

 

5、账户余额(折人民币)高于AAA账户的账户信息,返回账户代号、账户名称、币种、开户机构、账户余额;

我这个方法总感觉其实能有更简单的语法来解决。。。

 

 1 String sql = "SELECT * FROM "
 2                     + "(SELECT a.zhdh AS name, a.zhmc, a.bz, a.khjg, b.zhye, (b.zhye * c.hl) AS rmb_total "
 3                     + "FROM t_zhye b LEFT JOIN t_ckzh a "
 4                     + "ON a.zhdh = b.zhdh LEFT JOIN t_hl c "
 5                     + "ON a.bz = c.bz ) pp "
 6                     + "WHERE pp.rmb_total > (SELECT (b.zhye * c.hl)"
 7                     + "FROM t_zhye b LEFT JOIN t_ckzh a "
 8                     + "ON a.zhdh = b.zhdh LEFT JOIN t_hl c "
 9                     + "ON a.bz = c.bz "
10                     + "WHERE a.zhdh = 'AAA')";

 

 


经测试,以上返回的答案都是对的,但是其实语句还可以优化一点。

 

Written on Sept. 19th, 2019

你可能感兴趣的:(MySQL三表联查的例子)