对一段时间内的每一天进行查询,将其变成一个查询
我有这个:
public Map<Day,Integer> getUniqueLogins(long fromTime, long toTime) {
EntityManager em = emf.createEntityManager();
try {
Map<Day,Integer> resultMap = new ...;
for (Day day : daysInPeriod(fromTime, toTime)) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> q = cb.createQuery(Long.class);
// FROM UserSession
Root<UserSession> userSess = q.from(UserSession.class);
// SELECT COUNT(DISTINCT userId)
q.select(cb.countDistinct(userSess.<Long>get("userId")));
// WHERE loginTime BETWEEN ...
q.where(cb.between(userSess.<Date>get("loginTime"), day.startDate(), day.endDate()));
long result = em.createQuery(q).getSingleResult();
resultMap.put(day, (int) result);
}
return resultMap;
} finally {
em.close();
}
}
这对给定时间段内的每一天执行一个查询(该时间段是一个月的数量级)。
我可以在一次查询中获取这一特定数据吗?我正在使用 Hibernate/MySQL,但我不想需要任何非标准函数。
I have this:
public Map<Day,Integer> getUniqueLogins(long fromTime, long toTime) {
EntityManager em = emf.createEntityManager();
try {
Map<Day,Integer> resultMap = new ...;
for (Day day : daysInPeriod(fromTime, toTime)) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> q = cb.createQuery(Long.class);
// FROM UserSession
Root<UserSession> userSess = q.from(UserSession.class);
// SELECT COUNT(DISTINCT userId)
q.select(cb.countDistinct(userSess.<Long>get("userId")));
// WHERE loginTime BETWEEN ...
q.where(cb.between(userSess.<Date>get("loginTime"), day.startDate(), day.endDate()));
long result = em.createQuery(q).getSingleResult();
resultMap.put(day, (int) result);
}
return resultMap;
} finally {
em.close();
}
}
This executes a query for each day in a given period (the period being in the order of magnitude of a month).
Could I get this specific data in one query? I'm using Hibernate/MySQL, but I'd prefer not to need any non-standard functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须使用 MySQL 特定的函数来执行此操作。
from_days/to_days 会将登录时间转换为天数,然后返回日期时间,但小时/分钟/秒部分为零。
You'll have to use MySQL specific functions to do this.
The from_days/to_days will convert the loginTime to a number of days and then back to a datetime but with the hour/minute/second parts zero'd.
假设您的原始查询是:
这应该返回与在此期间每天运行原始查询相同的结果:
Assuming your original query is:
This should return the same results as running the original one per each day of the period:
GROUP BY LoginTime 的日期段计数不同的用户 ID。后端应该提供一种提取日期时间值的日期部分的方法。
GROUP BY the date segment of LoginTime counting distinct userids. The back-end should provide a way to extract the date-part of the datetime value.