我想选择 国家,其中一个人和 最旧/原始国家。 < / p>
此示例有2个表:
我在SQL中使用这样的东西:
SELECT p.COUNTRY, h.HISTORY
FROM COUNTRY AS c, HISTORY as h
WHERE c.ID = h.PERSON
AND h.ID = (SELECT MIN(h2.ID) FROM HISTORY as h2 WHERE h2.ID = name.ID)
我应该如何使用JPA执行此操作?(实体对象在我的问题的最后)。
SELECT p.country, p.historyEntity.history
FROM PersonEntity AS p
WHERE MIN(p.historyEntity.id)
谢谢!欢迎任何建议。
Table: PERSON
ID | Name | COUNTRY
------------------------------
1 | John | USA
2 | Maria | CANADA
3 | Peter | FRANCE
Table: HISTORY
ID | PERSON (FK)| HISTORY
------------------------------
1 | 1 | MEXICO
2 | 1 | BRASILIA
3 | 1 | USA
4 | 2 | GERMANY
5 | 2 | CANADA
6 | 3 | JAPAN
7 | 3 | KOREA
8 | 3 | USA
@Table(name = "PERSON")
public class PersonEntity {
@Id
@Column(name = "ID")
private long id;
@Column(name = "NAME")
private String name;
@Column(name = "COUNTRY")
private String country;
@OneToMany(mappedBy = "historyEntity")
private Set<HistoryEntity> historyEntities = new HashSet<HistoryEntity>(0);
...
}
@Table(name = "HISTORY")
public class HistoryEntity {
@Id
@Column(name = "ID")
private long id;
@ManyToOne()
@JoinColumn(name = "PERSON")
private PersonEntity personEntity;
@Column(name = "HISTORY")
private String history;
...
}
答案 0 :(得分:1)
我想你知道你的查询不起作用......试试这个:
SELECT p.country, h.history
FROM PersonEntity AS p
JOIN p.historyEntity h
WHERE h.id IN (SELECT MIN(h2.id) FROM HistoryEntity h2 where h2.historyEntity=p GROUP BY historyEntity)