1

我的问题是为什么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.日志

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
4

1 回答 1

3

这个要求没有意义。group by当 select 子句包含至少一个聚合函数(sum、avg、min、max 等)时使用。并且所有其他列必须出现在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
于 2013-03-15T08:32:12.470 回答