我的问题是为什么GROUP BY
没有显示在glassfish日志中。
我在下面添加了以下数据,因为有人想看到它
public List<Message> listAllMessageBySender(String currentUserID) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnit");
EntityManager entityManager = emf.createEntityManager();
TypedQuery<Message> eq = entityManager.createQuery("SELECT m FROM Message m WHERE m.sendBy.userId = :userid GROUP BY m.sendTo.userId", Message.class);
eq.setParameter("userid", Integer.parseInt(currentUserID));
List<Message> message = eq.getResultList();
return message;
}
Glassfish 3.1.2.Logs
FINE: SELECT id, message, send_date, send_by, send_to FROM message WHERE (send_by = ?)
bind => [50]
Data:
User A : sendBy.userId = 50
User B : sendTo.userId = 44
User C : sendTo.userId = 43
id send_date send_by send_to message
1 2013-03-14 14:58:46 44 50 50 send message to 44
2 2013-03-14 14:58:46 50 44 reply from 44 to 50
3 2013-03-14 17:38:52 44 50 2nd reply to 50
6 2013-03-14 18:22:10 50 44 44 reply to 50
7 2013-03-14 18:22:10 50 43 new
in the query above is i want to list all the user sent from User A. it causes duplication because there is two send_to 44. the xhtml below shows :
<ui:repeat value="#{messageController.items}" var="messageItem">
<br />
<div onclick="loadMessage()">
<h:panelGroup layout="block" >
<p:graphicImage height="50" width="50" value="#{messageItem.sendTo.profilePicture}"/>
</h:panelGroup>
<h:panelGroup layout="block" style="width: 270px;">
<h:outputText value="#{messageItem.sendTo.registerName}"/>
<h:panelGroup layout="block" style="float:right;">
<h:outputText value="#{messageItem.sendDate}" >
<f:convertDateTime pattern="HH:mm"/>
</h:outputText>
</h:panelGroup>
</h:panelGroup>
</div>
<p:remoteCommand name="loadMessageBean" action="#{messageController.loadMessage(messageItem.id)}" /> </ui:repeat>
ERD
User Table Message Table
user_id message_id
register_name send_date
send_to ----> referenced by user_id User Table
send_by ----> referenced by user_id User Table
答案 0 :(得分:3)
此请求没有意义。当select子句包含至少一个聚合函数(sum,avg,min,max等)时,使用group by
。所有其他列必须出现在group by
子句中。
例如,以下查询是有意义的:
SELECT max(m.length), sender.userId from Message m
inner join m.sendBy sender
GROUP BY sender.userId
对于每个邮件发件人,它将返回其最长邮件的长度。
请使用示例数据告诉我们您希望查询返回的内容。
如果您希望获得用户A向其发送消息的所有不同用户,则查询应该只是
select distinct m.sendTo from Message m
where m.sendBy.userId = :userid