如何为SELECT,WHERE和ORDER BY子句重新使用结果? [英] How to re-use result for SELECT, WHERE and ORDER BY clauses?

查看:126
本文介绍了如何为SELECT,WHERE和ORDER BY子句重新使用结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下查询返回我们附近的场所(纬度:62.0,lon:25.0),其范围内的半径按距离排序:

The following query returns the venues near us (lat: 62.0, lon: 25.0) inside whose radius we fall in ordered by distance:

SELECT *, 
     earth_distance(ll_to_earth(62.0, 25.0), 
     ll_to_earth(lat, lon)) AS distance 
FROM venues 
WHERE earth_distance(ll_to_earth(62.0, 25.0), ll_to_earth(lat, lon)) <= radius 
ORDER BY earth_distance(ll_to_earth(62.0, 25.0), ll_to_earth(lat, lon))

是否有可能(建议)重用 earth_distance(ll_to_earth(62.0,25.0),ll_to_earth(lat,lon)的结果)而不是分别为SELECT,WHERE和ORDER BY子句分别计算?

Is it possible (and advisable) to re-use the result from earth_distance(ll_to_earth(62.0, 25.0), ll_to_earth(lat, lon)) instead of computing it separately for SELECT, WHERE and ORDER BY clauses?

推荐答案

GROUP BY ORDER BY 子句,您可以引用列别名(输出列),甚至可以引用<$ c $的序数c> SELECT 列表项。我引用 ORDER手册BY

In the GROUP BY and ORDER BY clause you can refer to column aliases (output columns) or even ordinal numbers of SELECT list items. I quote the manual on ORDER BY:


每个表达式可以是输出的名称或序数列
(选择列表项)
,也可以是由
输入列值组成的任意表达式。

Each expression can be the name or ordinal number of an output column (SELECT list item), or it can be an arbitrary expression formed from input-column values.

粗体重点。

但是在 HAVING 子句,您只能引用基表中的列(输入列),因此您必须拼写出函数调用。

But in the WHERE and HAVING clauses, you can only refer to columns from the base tables (input columns), so you have to spell out your function call.

SELECT *, earth_distance(ll_to_earth(62.0, 25.0), ll_to_earth(lat, lon)) AS dist
FROM   venues 
WHERE  earth_distance(ll_to_earth(62.0, 25.0), ll_to_earth(lat, lon)) <= radius 
ORDER  BY distance;

如果您想知道将计算结果打包到 CTE 或子查询,只需使用 EXPLAIN ANALYZE 。 (我对此表示怀疑。)

If you want to know if it's faster to pack the calculation into a CTE or subquery, just test it with EXPLAIN ANALYZE. (I doubt it.)

SELECT *
FROM  (
   SELECT *
         ,earth_distance(ll_to_earth(62.0, 25.0), ll_to_earth(lat, lon)) AS dist
   FROM   venues
   ) x
WHERE  distance <= radius 
ORDER  BY distance;

@ Mike注释了,方法是声明函数 STABLE (或 IMMUTABLE ),您会通知查询计划者,函数调用的结果可以在单个语句中多次重复用于相同的调用。我引用了此处的手册

Like @Mike commented, by declaring a function STABLE (or IMMUTABLE) you inform the query planner that results from a function call can be reused multiple times for identical calls within a single statement. I quote the manual here:


一个STABLE函数无法修改数据库,并且保证

单条语句中所有行的给定参数相同的情况下返回相同的结果。此类别允许优化程序将
个函数的多次调用优化为单个调用

大胆强调我的观点。

这篇关于如何为SELECT,WHERE和ORDER BY子句重新使用结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆