Update:
LATERAL
合并允许加入,并采用Postgres 9.3. 。
The reason is in the error message. One element of the FROM
list cannot refer to another element of the FROM
list on the same level. It is not visible for a peer on the same level.
You could solve this with a correlated subquery:
SELECT *, (SELECT t FROM rp ORDER BY abs(rp.t - rq.t) LIMIT 1) AS ra
FROM rq
显然,你不在乎从 RP
中选择哪一行,从一组同样近的行中选择,所以我也这样做。
However, a subquery expression in the SELECT
list can only return one column. If you want more than one or all columns from the table RP
, use something like this subquery construct:
I assume the existence of a primary key id
in both tables.
SELECT id, t, (ra).*
FROM (
SELECT *, (SELECT rp FROM rp ORDER BY abs(rp.t - rq.t) LIMIT 1) AS ra
FROM rq
) x;
相关子查询对“ 强势” 坏表现 < / 强” 来说是臭名昭著的。 这种查询 — — 在计算您想要的东西的同时显然计算 — — 将特别 suck < / em >, 因为 < code>rp.t - rq.t code> 的表达方式不能使用索引。 更大的表格会使性能急剧恶化 。
此重写查询应该能够使用 RP.t 上的“ 强” 索引, 该索引应使用大表格 强 > 更快的“ 强” 。
WITH x AS (
SELECT *
,(SELECT t
FROM rp
WHERE rp.t < rq.t
ORDER BY rp.t DESC
LIMIT 1) AS t_pre
,(SELECT t
FROM rp
WHERE rp.t >= rq.t
ORDER BY rp.t
LIMIT 1) AS t_post
FROM rq
)
SELECT id, t
,CASE WHEN (t_post - t) < (t - t_pre)
THEN t_post
ELSE COALESCE(t_pre, t_post) END AS ra
FROM x;
再说一遍,如果你想要整排:
WITH x AS (
SELECT *
,(SELECT rp
FROM rp
WHERE rp.t < rq.t
ORDER BY rp.t DESC
LIMIT 1) AS t_pre
,(SELECT rp
FROM rp
WHERE rp.t >= rq.t
ORDER BY rp.t
LIMIT 1) AS t_post
FROM rq
), y AS (
SELECT id, t
,CASE WHEN ((t_post).t - t) < (t - (t_pre).t)
THEN t_post
ELSE COALESCE(t_pre, t_post) END AS ra
FROM x
)
SELECT id AS rq_id, t AS rq_t, (ra).*
FROM y
ORDER BY 2;
请注意使用具有复合型号 < / 坚固> 的“ 强性外壳” 。这里没有多余的paren 。在手册< a href=" http://www. panggresql.org/docs/product/interactive/sql- 表达式.html#FIELD- SELECETION' rel="nreferrer" >这里 和 < a href=" http://www. postergresql.org/docs/current/interactive/rowtyms.html#AEN7249" rel=" noreferr">。
以 PostgreSQL 9.1. 测试。 < a href="http://sqlfiddle.com/#!1/fdea1/1, rel=“ noreferrer” > Demo on sqlfiddle.