如何创建“一对多” sql查询语句

时间:2019-06-20 09:27:46

标签: mysql sqlite

我有一个名为(center_info)的表,该表具有学生的信息以及所支付的总账单和总余额。另一个名为(center_payments)的表,其中记录了学生支付的每个账单日期。
我想将学生在表1(center_info)中的记录加入到他在表2(center_payments)中支付账单的每个日期

以下是center_info中的记录:

id | student | term | bill | total_paid | total_balance | last_date_of_pymt |
---+---------+------+------+------------+---------------+-------------------+
 5    mary      1     400        200         -200            6 / june / 2019
 6    john      1     500        300         -200            2 / june / 2019
 7    grace     2     450        400         -50          17 / august / 2019
 8    mike      2     450        100         -350         15 / august / 2019

以下是center_payments中不同的付款日期:

id | student | paid | balance |     date     | term |
---+---------+------+---------+--------------+------+
5     mary     100     -300    3 / june /2019    1
5     mary     100     -200    6 / june /2019    1
6     john     150     -350    1 / june /2019    1
6     john     150     -200    2 / june /2019    1 
7     grace    400     -50     17 / aug /2019    2
8     mike     50      -400    5 / aug /2019     2
8     mike     50      -350    5 / aug /2019     2

我想将表1中的学生记录和表2中的所有个人付款合并在一起,其中term(column)= 1

当前只能使用以下代码打印出所选学生并查看两个表中的所有记录:

int row = c_FirstTerm.getSelectedRow();
            try{
            String table_click=(c_FirstTerm.getModel().getValueAt(row,0).toString());    
            String sgl="select center_info.id,center_info.student,center_info.bill,center_info.Term,center_info.total_paid,center_info.total_balance,center_info.last_date_of_pymt,center_payments.paid,center_payments.balance,center_payments.date from center_info INNER JOIN center_payments on center_info.term=center_payments.term and center_info.id=center_payments.id and center_info.Student='"+table_click+"'";
        }catch(Exception e){
            JOptionPane.showMessageDialog(null,e);
        }

但是假设我没有选择特定的学生,我如何从term = 1的两个表中为学生及其个人付款建立一对多关系。例如这样:

//first group
id | student | paid | balance |     date     | term |
---+---------+------+---------+--------------+------+
5     mary     100     -300    3 / june /2019    1
5     mary     100     -200    6 / june /2019    1

id | student | term | bill | total_paid | total_balance | last_date_of_pymt |
---+---------+------+------+------------+---------------+-------------------+
 5    mary      1     400        200         -200            6 / june / 2019
_____________________________________________________________________________

//next group
id | student | paid | balance |     date     | term |
---+---------+------+---------+--------------+------+
6     john     150     -350    1 / june /2019    1
6     john     150     -200    2 / june /2019    1

id | student | term | bill | total_paid | total_balance | last_date_of_pymt |
---+---------+------+------+------------+---------------+-------------------+
 6    john      1     500        300         -200            2 / june / 2019

0 个答案:

没有答案