我有一个包含属性数据的表,每个属性可以有多个按日期记录的条目。我想在表中添加一个标记当前条目的列,以便更容易选择。像col name这样的东西是current_record = Y。
我尝试过的; 创建仅选择最新记录的视图,然后使用该视图
UPDATE properties
SET current_record = 'Y'
FROM current_properties
WHERE current_properties.building_reference_number = properties.building_reference_number;
两者都有building_reference_number
索引,类型为整数。这导致434537.04的成本似乎非常高。 properties
是15.6米行current_properties
是12.8米。
我尝试了第二种方法而没有创建视图;
UPDATE properties
SET current_record = 'Y'
WHERE inspection_date IN (
SELECT inspection_date FROM properties
WHERE inspection_date IN (SELECT distinct on (building_reference_number)inspection_date )
ORDER BY inspection_date desc
FOR UPDATE
但是这个成本更高。这是第一种方法的解释,对postgres来说是新手
Update on properties (cost=434537.04..4930742.06 rows=15019542 width=608)
-> Hash Join (cost=434537.04..4930742.06 rows=15019542 width=608)
Hash Cond: (properties.building_reference_number = yy_current_epc_dmv.building_reference_number)
-> Seq Scan on properties (cost=0.00..2233904.25 rows=17313725 width=378)
-> Hash (cost=210745.13..210745.13 rows=12874313 width=14)
-> Seq Scan on current_properties (cost=0.00..210745.13 rows=12874313 width=14)
查看定义是; SELECT DISTINCT ON(properties.building_reference_number)properties.building_reference_number, properties.inspection_date FROM属性 ORDER BY properties.building_reference_number,properties.inspection_date DESC;