2014-02-20 71 views
0

我有一個簡單的表:查詢返回多個對象時,只有一個預計

+-------------------+--------------+------+-----+---------+-------+ 
| Field    | Type   | Null | Key | Default | Extra | 
+-------------------+--------------+------+-----+---------+-------+ 
| ID    | bigint(20) | NO | PRI | NULL |  | 
| AdmissionDateTime | datetime  | NO |  | NULL |  | 
| AdmissionEvent | varchar(255) | YES |  | NULL |  | 
| DischargeDateTime | datetime  | YES |  | NULL |  | 
| DischargeEvent | varchar(255) | YES |  | NULL |  | 
| DemographicId  | bigint(20) | NO | MUL | NULL |  | 
| FacilityId  | bigint(20) | YES | MUL | NULL |  | 
| VisitId   | bigint(20) | NO | MUL | NULL |  | 
| WardId   | bigint(20) | NO | MUL | NULL |  | 
+-------------------+--------------+------+-----+---------+-------+ 

在我運行下面的JPA(Spring的數據)查詢:

@Query("SELECT w FROM WardTransaction w WHERE w.id = (SELECT MAX(x.id) FROM 
WardTransaction x WHERE w = x AND w.visit = :visit)") 
public WardTransaction findCurrent(@Param("visit") Visit visit); 

偶爾我得到以下例外。

org.springframework.dao.IncorrectResultSizeDataAccessException: More than one 
result was returned from Query.getSingleResult(); nested exception is 
javax.persistence.NonUniqueResultException: More than one result was returned from 
Query.getSingleResult() 

我還沒有弄清楚爲什麼會發生這種情況。這對我來說似乎沒有什麼意義,因爲只能有一個'MAX' - 尤其是在Id(我過去曾使用'admissionDate')。

任何協助讚賞。

回答

0

你爲什麼選擇餐桌?你應該選擇列。

試試這個

@Query("SELECT * FROM WardTransaction w WHERE w.id in (SELECT MAX(x.id) 
    FROM WardTransaction x WHERE w.id = x.id AND w.visit = :visit)") 
0

這個查詢比較簡單,我想會得到你想要的東西:

SELECT something 
FROM sometable 
Where something = someotherthing 
ORDER BY sometable.id DESC 
LIMIT 1 

基本上它返回與頂部的最高ID的結果,並抓住第一一。

相關問題