用几个表实现JOIN

时间:2019-09-29 22:00:38

标签: java mysql sql jpa jpql

我有这个表,我想从中选择许多行并使用JOIN以便将id转换为来自两个表的名称。我尝试过:

主表:

@Entity
@Table(name = "payment_transactions")
public class PaymentTransactions implements Serializable {
    ..... 
    @Column(length = 4)
    private Integer merchant_id;

    @Column(length = 4)
    private Integer terminal_id; 
    ......
}

带有其他数据的表:

@Entity
@Table(name = "merchants")
public class Merchants implements Serializable {

    @Column(name = "id")
    private int id;

    @Column(length = 255)
    private String name;
    .........
}


@Entity
@Table(name = "terminals")
public class Terminals implements Serializable {

    @Column(name = "id")
    private int id;

    @Column(length = 255)
    private String name;
    .........
}

我尝试过:

String hql = "select e.* from " + PaymentTransactions.class.getName() + " e "
                + " INNER JOIN " + Merchants.class.getName() + " m "
                + " ON e.id = m.merchant_id AND " 
                + " INNER JOIN " + Terminals.class.getName() + " t "
                + " ON e.id = t.terminal_id "
                + " where e.created_at >= :start_date and e.created_at <= :end_date";

总体思路是,我想要一个主表Payment transactions,其中存储着merchant_idterminal_id作为数字。通过join,我想获得商家和终端的名称。实施此操作的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您只需要将这些变量添加到查询的列列表中即可:

String hql = "select e.*, m.name AS merchant, t.name AS terminal"
                + " FROM " + PaymentTransactions.class.getName() + " e "
                + " INNER JOIN " + Merchants.class.getName() + " m "
                + " ON e.id = m.merchant_id AND " 
                + " INNER JOIN " + Terminals.class.getName() + " t "
                + " ON e.id = t.terminal_id "
                + " where e.created_at >= :start_date and e.created_at <= :end_date";

请注意,您将需要添加列别名,以避免在输出结果中两次具有相同的列名(name)。查询包含这些内容(例如m.name AS merchant),因此您在获取结果时可以将商家名称作为merchant列访问。