SQL相同的两个子查询如何复用?

select sc.col1, sc.col2 
    from 
    **(select col1,col from t1)** sc 
            where sc.col1 = (select max(col)
            from 
                **(select col1,col from t1)**);

例如上面这种情况,在sql语句中出现两个一模一样的查询语句,在实际执行的时候会执行两次。
当然可以先将要复用的先查出来弄成临时表可以解决,但是如何用一条SQL语句来达到复用的效果,让查询优化器自动复用呢?

阅读 8.4k
2 个回答

postgresql 实现方式

with tmp_q as (
    select col1,col from t1
)
select sc.col1, sc.col2 
    from tmp_q sc 
            where sc.col1 = (select max(col) from tmp_q);

不就是想取出 col 最大的那些行么:

select * from t
where col = (select max(col) from t)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题