解決hibernate Subquery returns more than 1 row

使用hibernate時,發現一個錯誤:

        at java.lang.Thread.run(Thread.java:748)

Caused by: java.sql.SQLException: Subquery returns more than 1 row

        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:54

 

SQL:

select
  inspection0_.houseInfo_id as col_0_0_,
  inspection0_.id as col_1_0_,
  inspection0_.agent_id as col_2_0_,
  (select
     distinct cooperatio2_.id
   from
     t_cooperationOrder cooperatio2_
   where
     cooperatio2_.primaryAgent_id=113
     and cooperatio2_.status>1
     and cooperatio2_.inspectionOrder_id=inspection0_.id ) as col_3_0_,
  houseinfo1_.id as id1_35_0_,
  inspection0_.id as id1_40_1_,
  houseinfo1_.address as address2_35_0_,
  houseinfo1_.agreeTotalPrice as agreeTot3_35_0_
from
  t_inspectionOrder inspection0_
  inner join
  t_houseInfo houseinfo1_
    on inspection0_.houseInfo_id=houseinfo1_.id
where
  (
    inspection0_.agent_id=113
    or 113 in (
      select
        cooperatio3_.secondaryAgent_id
      from
        t_cooperationOrder cooperatio3_
      where
        cooperatio3_.inspectionOrder_id=inspection0_.id
        and cooperatio3_.status>1
    )
  )
  and houseinfo1_.houseStatus=8
  and (
    inspection0_.status in (
      7 , 8
    )
  )
order by
  inspection0_.updateTime desc

 

解決方法:

以select * from table1 where table1.colums=(select columns from table2);這個sql語句爲例。

1)如果是寫入重複,去掉重複數據。然後寫入的時候,可以加邏輯判斷(php)或者外鍵(mysql),防止數據重複寫入。
   (我實際開發中遇到的就是數據重複寫入的情況,在數據庫查到有相同的數據兩條,這不符原本的原本的業務需求)
2)在子查詢條件語句加limit 1,找到一個符合條件的就可以了
select * from table1 where table1.colums=(select columns from table2 limit 1);
3)在子查詢前加any關鍵字
select * from table1 where table1.colums=any(select columns from table2);

(4)select * from table1 where table1.colums=any(select max(columns) from table2);

參考:

https://hedleyproctor.com/2014/08/hibernate-query-limitations-and-correlated-sub-queries/

https://blog.csdn.net/LY_Dengle/article/details/78028166

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章