我有这个表,我想从中选择许多行并使用 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_id
和terminal_id
存储为数字。通过加入,我想获取商家和终端的名称。实现这个的正确方法是什么?
最佳答案
您只需将这些变量添加到查询中的列列表中即可:
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 ASmerchant
),以便您在获取结果时可以将商家名称作为 merchant
列进行访问。
关于java - 实现多个表的 JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58159532/