0

我需要合并来自两个不同查询的结果,以便按 dateCreated 对结果进行排序。

我想要做:

def query = """ 
  select user from 
   (select v.user, v.dateCreated from Vote as v where v.item=:item order by v.dateCreated desc) as myvotes, 
   (select c.user, c.dateCreated from Comment as c where c.item=:item order by c.dateCreated desc) as mycomments

def item = // some item
tmpUsers = Message.executeQuery (query, [item: item])  

如何合并两个查询?

4

2 回答 2

1
def index() {
        def query1 = """ 
                    select new Map(v.user as user, v.dtCreated as dtCreated) from Vote as v where v.item = :item
                    """
        def query2 = """ 
                    select new Map(c.user as user, c.dtCreated as dtCreated) from Comment as c where c.item = :item
                    """                 

        def result1 = Vote.executeQuery(query1, [item: 'A'])
        def result2 = Comment.executeQuery(query2, [item: 'A'])

        def mergedList = ([] << result1 << result2)?.flatten()?.sort{a,b -> b.dtCreated <=> a.dtCreated}
        render mergedList as grails.converters.JSON
    }

我同意 HQL 中没有适当的 UNION。如果Vote无法连接,Comment则上述实现(2 个简单查询而不是 1 个复杂查询)将提供预期的结果。

假设,

class Vote {
    String item
    Date dtCreated
    String user
}

class Comment {
    String item
    Date dtCreated
    String user
}

//Bootstrap
def vote1 = new Vote(item: "A", dtCreated: new Date(), user: 'user1')
def vote2 = new Vote(item: "A", dtCreated: new Date() + 1, user: 'user2')
def vote3 = new Vote(item: "A", dtCreated: new Date() + 2, user: 'user3')

def comment1 = new Comment(item: "A", dtCreated: new Date(), user: 'user4')
def comment2 = new Comment(item: "A", dtCreated: new Date() - 4, user: 'user5')
def comment3 = new Comment(item: "A", dtCreated: new Date() - 6, user: 'user6')

[vote1, vote2, vote3, comment1, comment2, comment3]*.save(flush: true, failOnError: true)

//Output Json:
[
    {
        "dtCreated": "2013-06-23T13:49:24Z",
        "user": "user3"
    },
    {
        "dtCreated": "2013-06-22T13:49:24Z",
        "user": "user2"
    },
    {
        "dtCreated": "2013-06-21T13:49:24Z",
        "user": "user4"
    },
    {
        "dtCreated": "2013-06-21T13:49:24Z",
        "user": "user1"
    },
    {
        "dtCreated": "2013-06-17T13:49:24Z",
        "user": "user5"
    },
    {
        "dtCreated": "2013-06-15T13:49:24Z",
        "user": "user6"
    }
]
于 2013-06-21T03:23:58.320 回答
0

您可以使用 hibernate-pojo 样式来获取 Vote 和 Comment 对象的集合并将它们合并到 java 中。例如:

List<User> mergedUsers = new LinkedList<User>();

List<Vote> votes = voteDAO.getVotes();
List<Comment> comments = commentDAO.getComments();

for(Vote vote : votes) mergedUsers.add(new User(vote));
for(Comment comment : comments) mergedUsers.add(new User(comment));

或者您可以使用 SQL“UNION”关键字发出本机 jdbc 查询并将结果映射到您的任何结果对象(用户对象?)

于 2013-06-21T02:02:03.807 回答