我正在从SQL Server迁移到Postgres,并且在大多数情况下一切正常。问题之一是我无法弄清楚如何使此查询在Postgres中工作:
update
"Measure"
set
DefaultStrataId = StrataId
FROM (SELECT "Strata"."MeasureId",
Min("Strata"."index") AS "Index"
FROM "Strata",
"Measure"
WHERE "Strata"."MeasureId" = "Measure"."MeasureId" and "Strata"."StrataId" in (select strataid from point)
GROUP BY "Strata"."MeasureId") a
INNER JOIN strata
ON "Strata"."index" = a."index"
where "Strata"."MeasureId" = "Measure"."MeasureId";
它抱怨:SQL Error [42601]: ERROR: syntax error at or near "FROM"
如何使它工作?
答案 0 :(得分:0)
您可以为此使用DISTINCT ON来简化它。
子查询中的ORDER BY将确保它是最小“索引”的“ StrataId”。
UPDATE "Measure" m
SET "DefaultStrataId" = q."StrataId"
FROM
(
SELECT DISTINCT ON (s."MeasureId") s."MeasureId", s."index", s."StrataId"
FROM "Strata" s
JOIN "Point" p ON p."StrataId" = s."StrataId"
JOIN "Measure" m ON m."MeasureId" = s."MeasureId"
ORDER BY s."MeasureId", s."index"
) q
WHERE q."MeasureId" = m."MeasureId";
在 db <>小提琴here
上进行测试顺便说一句,下面的查询也适用于该提琴中的测试数据。
基本上,在Postgresql中,引用名称与不引用名称是不同的。
在这方面,MS Sql Server的容忍度更高。
UPDATE "Measure"
SET "DefaultStrataId" = "StrataId"
FROM (SELECT "Strata"."MeasureId",
Min("Strata"."index") AS "index"
FROM "Strata",
"Measure"
WHERE "Strata"."MeasureId" = "Measure"."MeasureId" and "Strata"."StrataId" in (select "StrataId" from "Point")
GROUP BY "Strata"."MeasureId") a
INNER JOIN "Strata"
ON "Strata"."index" = a."index"
where "Strata"."MeasureId" = "Measure"."MeasureId";
答案 1 :(得分:0)
笨拙。在@wildplasser感到羞耻以至于我的查询变得令人厌恶之后,一切都神奇地开始了。除了切换到标准联接并添加别名外,这与我没有做任何更改一样
update
"Measure" m set
"DefaultStrataId" = "StrataId"
from
(
select
s."MeasureId",
min(s."Index") as "Index"
from
"Measure" m
inner join "Strata" s on
s."MeasureId" = m."MeasureId"
where s."StrataId" in (
select
s."StrataId"
from
"Point")
group by
s."MeasureId") a
inner join "Strata" s on
s."Index" = a."Index"
where
s."MeasureId" = m."MeasureId";
答案 2 :(得分:0)
您唯一的目标似乎是从Strata获得最低价值
省略所有丑陋的引号,并添加一些别名(假设仅存在一个带有最小值的记录):
UPDATE Measure m
SET DefaultStrataId = s.StrataId
FROM Strata s
WHERE s.MeasureId = m.MeasureId
AND NOT EXISTS (
SELECT * FROM Strata nx
where nx.MeasureId = s.MeasureId
AND nx."index" < s."index"
)
;