查询失败,除非我重新排序 SELECT 语句中的值

Query failing unless I reorder the values in SELECT statement

我正在尝试执行 HQL 查询,但我不明白为什么如果我不对 SELECT 语句中的值重新排序,查询就会失败

以下查询无效

查询 1

@Query("SELECT uf.flight.arrivalAirport.iataCode, uf.flight.flightStatus " +
        "FROM UserFlight uf WHERE uf.flight.id=?1 AND uf.user.id=?2")

生成SQL

select airport2_.iata_code as col_0_0_, 
flight1_.flight_status_id as col_1_0_, 
flightstat4_.id as id1_6_, 
flightstat4_.code as code2_6_, 
flightstat4_.description as descript3_6_ 
from user_flight userflight0_, 
flight flight1_, 
airport airport2_ 
inner join flight_status flightstat4_ 
on flight1_.flight_status_id=flightstat4_.id 
where userflight0_.flight_id=flight1_.id 
and flight1_.arrival_airport_id=airport2_.id 
and userflight0_.flight_id=? 
and userflight0_.user_id=?

异常

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'flight1_.flight_status_id' in 'on clause'

如果我将查询更改为以下内容(只是重新排序 SELECT 值)

查询 2

@Query("SELECT uf.flight.flightStatus, uf.flight.arrivalAirport.iataCode " +
        "FROM UserFlight uf WHERE uf.flight.id=?1 AND uf.user.id=?2")

生成SQL

select flight1_.flight_status_id as col_0_0_, 
airport4_.iata_code as col_1_0_, 
flightstat2_.id as id1_6_, 
flightstat2_.code as code2_6_, 
flightstat2_.description as descript3_6_ 
from user_flight userflight0_, 
flight flight1_ 
inner join flight_status flightstat2_ 
on flight1_.flight_status_id=flightstat2_.id, 
airport airport4_ 
where userflight0_.flight_id=flight1_.id 
and flight1_.arrival_airport_id=airport4_.id 
and userflight0_.flight_id=? 
and userflight0_.user_id=? 

有效,我从数据库中获取结果。

谁能告诉我为什么其中一个有效而另一个无效?

注意:FlightStatus 是一个实体,而不是字符串值。

错误在这里:

在您的第一个查询中:

...
airport airport2_ 
inner join flight_status flightstat4_ 
on flight1_.flight_status_id=flightstat4_.id 
...

所以解释器认为你想要 link airport2_flighstat4_,所以 ON 子句不正确

相反,在第二个查询中,您有:

...
flight flight1_ 
inner join flight_status flightstat2_ 
on flight1_.flight_status_id=flightstat2_.id, 
...

关于两个表 flight1_flighstat2_

的 ON 子句是正确的

编辑

当你写:

SELECT uf.flight.arrivalAirport.iataCode, uf.flight.flightStatus

解释器按以下顺序分解对象:

处理第一个字段:

uf (user_flight) -> flight (flight) -> arrivalAirport (airport)

所以处理第二个字段:

uf (user_flight) -> flight (flight)

这两个对象已经存在于表格中,因此它会重用它们,但是,JOIN 的顺序已经定义,因此您有第一个布局(有错误)。

当您更改字段顺序时,(第一个查询的)第二个字段已由第一个字段处理,旧的第一个字段作为第二个字段处理,因此您的第二个 lasyout 没有错误。

我希望,我的解释是干净的:)