【问题标题】:taking a very efficient join between two tables in Oracle在 Oracle 中的两个表之间进行非常有效的连接
【发布时间】:2013-06-21 01:41:22
【问题描述】:

我有包含数百万数据的大表(它太大了)。

表格如下

Post
post_id,user_id,description,creation_date, xyz, abc ,etc

primarykey for post :post_id
partition key for Post : creation_date
index on Post : user_id

Comment:
commentid,post_id, comment_creation_date,comment_type,last_modified_date

Primary key of comment = commentid
indexed colums on Comment = commentid, postid
partition key for Comment table =  comment_creation_date

注意:我不能以任何方式建立新索引而不改变表架构

评论类型是字符串

现在给定一个comment_type 列表和一个comment_creation_date 范围,我需要找到所有具有该comment_type 类型的帖子。

一个简单的非常低效的解决方案将是

    select * from post p, comment c where c.post_id = p.post_id where c.comment_creation_date > ? and c.comment_creation_date < ?
and p.posttype IN (some list)

如何优化这个查询? 如果通过评论的 last_modified_date 而不是comment_date 来做同样的事情怎么办。 注意:

last_modified_date is NOT indexed and comment_date Is

一旦查询成功,我想将一个帖子的所有 cmets 放在一起。 例如 post1 与 c1,c2,c3

PS:我不擅长设计查询。我知道 IN 不利于性能。

【问题讨论】:

  • 如果这还不够快,我不确定您是否能够在不以任何方式更改架构的情况下获得更快的速度。模式是性能的一个非常重要的部分。您可以尝试 SELECT * FROM post WHERE EXISTS (SELECT NULL FROM comment WHERE ...) 但我很确定性能会相似。

标签: sql oracle optimization query-optimization


【解决方案1】:

我不确定这是否会节省时间,但也许将您的评论部分移至子查询会有所帮助:

SELECT *
FROM Post p
JOIN (SELECT *
      FROM Comment
      WHERE comment_creation_date > ? and comment_creation_date < ?
              AND 'stringlist' LIKE '%'||comment_type||'%'
     )c
ON c.post_id = p.post_id

【讨论】:

    【解决方案2】:

    您的查询在语法上不正确,因为它有两个 where 子句。此外,您在代码中引用了comment_type,但在代码中引用了post_type。我假设后者。您可以将其重写为:

    select *
    from post p, comment c
    where c.post_id = p.post_id and
          c.comment_creation_date > ? and c.comment_creation_date < ? and
          p.posttype IN (some list)
    

    Oracle 有一个很好的优化器,所以没有理由认为它会优化得很差。

    虽然对性能没有影响,但 ANSI 标准连接语法是编写查询的更好方法:

    select *
    from post p join
         comment c
         on c.post_id = p.post_id
    where c.comment_creation_date > ? and c.comment_creation_date < ? and
          p.posttype IN (some list)
    

    优化可以决定何时进行哪些过滤以及如何进行连接。您可以通过在comment(comment_creation_date, post_id) 和可能在post(post_type) 上设置索引来提高任一版本的效率(后者取决于您拥有多少不同的帖子类型,称为索引的选择性)。

    我不确定您所说的“我知道 IN 不利于性能”是什么意思。这不是常识。请分享您对此的任何参考。据我所知,带有一堆常量的in 的性能应该不会比像p.posttype = &lt;value1&gt; or p.posttype = &lt;value2&gt; . . . 这样的一堆表达式差。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多