[英]how to write inner join a selected table query in hibernate.ejb
I have a query working fine:我有一个查询工作正常:
StringBuilder query = new StringBuilder(
"select o.deviceName, o.deviceOs, o.loginOn, e.username, e.name, e.idNo from LoginHistory o, User e ");
query.append(" where o.userId = e.userId");
Query q = getEm().createQuery(query.toString());
This createQuery()
will go to createQuery() in class org.hibernate.ejb.AbstractEntityManagerImpl
.此
createQuery()
将 go 到 class org.hibernate.ejb.AbstractEntityManagerImpl
中的 createQuery() 。
I want to edit the query to get the last login for each user.我想编辑查询以获取每个用户的最后一次登录。 The following SQL query can run in a db2 command successfully:
以下 SQL 查询可以在 db2 命令中成功运行:
select m1.*, m2.*
from tibs.LoginHistory m1 inner join (
select userId, max(loginOn) as loginOn from tibs.LoginHistory group by userId
) m2
on m1.userId = m2.userId and m1.loginOn = m2.loginOn;
But when I try to apply this in my code above, it will hit QuerySyntaxException: unexpected token:
at (
after inner join
.但是当我尝试在上面的代码中应用它时,它会遇到
QuerySyntaxException: unexpected token:
at (
after inner join
。
Code is something like:代码类似于:
StringBuilder query = new StringBuilder(
"select o.deviceName, o.deviceOs, o.loginOn, e.username, e.name, e.cif, e.idNo from LoginHistory o, ECUser e ");
query.append("inner join (select o2.userId, o2.max(loginOn) as loginOn from LoginHistory group by userId) o2 ");
query.append("on o.userId = o2.userId and o.loginOn = o2.loginOn");
query.append(" where o.userId = e.userId");
Is this workable in this way?以这种方式可行吗? If yes, what syntax should I use?
如果是,我应该使用什么语法?
Or does Hibernate not accept this, and I need to do it in another way?还是 Hibernate 不接受这个,我需要用另一种方式来做?
Add on** Even I change my query to this, still the same:添加**即使我将查询更改为此,仍然相同:
StringBuilder query = new StringBuilder(
"select o.deviceName, o.deviceOs, o.loginOn, e.username, e.name, e.cif, e.idNo from LoginHistory o, ECUser e ");
query.append("inner join (select o2.userId, o2.max(loginOn) as loginOn from LoginHistory o2 group by userId) ");
query.append("on o.userId = o2.userId and o.loginOn = o2.loginOn");
query.append(" where o.userId = e.userId");
I think the inner query should be as follows (note position of o2
):我认为内部查询应该如下(注意
o2
的 position ):
(select o2.userId, o2.max(loginOn) as loginOn from LoginHistory o2 group by userId)
Please name variables appropriately to facilitate comprehension.请适当命名变量以方便理解。
It would be helpful if o2
was renamed to lh
, since it represents LoginHistory
entity.如果将
o2
重命名为lh
会很有帮助,因为它代表LoginHistory
实体。
(select lh.userId, lh.max(loginOn) as loginOn from LoginHistory lh group by userId)
You can use the following query:您可以使用以下查询:
select o.deviceName, o.deviceOs, o.loginOn, e.username, e.name, e.idNo
from LoginHistory o, User e
where o.id = (select max(lh.id) from LoginHistory lh where lh.userId = e.userId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.