我有两张桌子:
PERSON
与列person_id
和total
DATA
列data_a
,data_b
,data_c
, 和data_person_id
每个“人”可以有零个或多个条目DATA
- 您的标准一对多关系。PERSON
有一total
列是 中的值的总和DATA
。目前在正确但错误的地方total
与实际条目之间存在一些差异。DATA
DATA
total
这是我用来查找差异的查询:
SELECT
person_id
FROM PERSON JOIN (
SELECT
data_person_id,
SUM( data_a + data_b + data_c ) as data_total
FROM
DATA
GROUP BY
data_person_id
) x ON data_person_id = person_id
WHERE
person_total != data_total
我计划通过 Hibernate 作为后端将是 Postgres 9.x 的查询来执行此操作。
我试图理解/修复的错误查询是:
UPDATE
ONLY PERSON
SET
total = data_info.calc_total
FROM (
SELECT
SUM( data_a + data_b + data_c ) as calc_total
FROM
DATA
WHERE
DATA.data_person_id = person_id
GROUP BY
DATA.data_person_id
) as data_info
WHERE
PERSON.person_id IN (
SELECT
data_person_id
FROM PERSON JOIN (
SELECT
data_person_id,
SUM( data_a + data_b + data_c ) as data_total
FROM
DATA
GROUP BY
data_person_id
) x ON person_id = data_person_id
WHERE
total != data_total
)
现在,它不会运行,因为WHERE DATA.data_person_id = person_id
. 但如果我把它拿出来,就会使用错误的值。
以下似乎有效,但我对为什么感到困惑:
UPDATE
ONLY PERSON
SET
total = data_info.calc_total
FROM
PERSON P JOIN (
SELECT
data_person_id,
SUM( data_a + data_b + data_c ) as calc_total
FROM
DATA
WHERE
DATA.data_person_id = person_id
GROUP BY
DATA.data_person_id
) as data_info ON P.person_id = data_person_id
WHERE
PERSON.person_id IN (
SELECT
data_person_id
FROM PERSON JOIN (
SELECT
data_person_id,
SUM( data_a + data_b + data_c ) as data_total
FROM
DATA
GROUP BY
data_person_id
) x ON person_id = data_person_id
WHERE
total != data_total
)
我相信我的问题在于我对文档的误解(我猜测关于自加入的部分)。
此外,感谢任何改进此查询的方法!