【问题标题】:Subquery in from clause using HQL使用 HQL 在 from 子句中的子查询
【发布时间】:2014-02-12 14:24:12
【问题描述】:

我有一个表 articles 有 500k 行。一篇文章有​​一个作者列表。我正在尝试创建一个查询来获取作者列表的最新发表文章。

我使用了以下 HQL 查询,它得到了我想要的,但运行速度很慢(~4s)

            select author, article
            from Article article inner join article.authors author
            where (author.id, article.publishedAt) in 
            (select author.id, max(article.publishedAt) 
            from Article article join article.authors author
            where author.id in (authors_list))
            group by author.id

在普通 sql 中可能更好的查询是:

              select * from (
                select articles.id, author.id
                from articles, article_authors, authors
                where articles.id = article_authors.article_id and 
                    article_authors.author_id=authors.id    
                    and author.id in (author_list)  
                    order by articles.publishedAt desc
              ) b
              group by authors.id;

但是从 Hibernate 文档中可以看出,HQL 子查询只能出现在 select 或 where 子句中。 http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-subqueries

有没有办法使用 HQL 或其他方式来模拟这种查询以提高查询的性能?

【问题讨论】:

标签: sql hibernate hql


【解决方案1】:

在任何一种情况下,您都想尝试分离您用来比较的数据(如果它很大)。在上面的第一个查询中,您有:

in 
            (select author.id, max(article.publishedAt) 
            from Article article join article.authors author
            where author.id in (authors_list))

尝试先将该语句放入临时表中,然后使用该小数据集来提高效率。 所以它看起来像:

select author.id, max(article.publishedAt) into #temp1
                from Article article join article.authors author
                where author.id in (authors_list))

 select author, article
            from Article article inner join article.authors author
            where (author.id, article.publishedAt) in 
            (select author.id, article.publishedAt 
            from #temp1)
            group by author.id

因为计算完成,然后数据集更小,它应该会提高性能。

【讨论】:

    猜你喜欢
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2019-04-22
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多