欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决hibernate Subquery returns more than 1 row

程序员文章站 2022-07-11 16:30:12
...

使用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