2
我在我的數據庫中有地址和定價數據。定價數據不完整,通常適用於某個地區,其他時間適用於特定地址。我有一個plpgsql函數可以檢索最準確的價格數據。我目前在我的功能中有:選擇postgreSQL中最準確的數據?
SELECT price_est.sau_price_avg INTO _est_price FROM price_est WHERE price_est.neighbourhood_id = _neighbourhood_id AND --neighbourhood level
price_est.district_id = _district_id AND
price_est.municipality_id = _municipality_id AND
price_est.county_id = _county_id;
IF _est_price IS NULL THEN
SELECT price_est.sau_price_avg INTO _est_price FROM price_est WHERE price_est.neighbourhood_id IS NULL AND --district level
price_est.district_id = _district_id AND
price_est.municipality_id = _municipality_id AND
price_est.county_id = _county_id;
END IF;
...
如果數據在某處不可用,那麼沒有對該區域的外鍵引用。
這對我來說似乎是一個非常笨拙的解決方案。有一個更好的方法嗎?
我可以對錶格進行更改,並且數據表示是必要的。
-----------------------------------編輯---------- -------------------------
我做了尼克巴恩斯的回答爲我工作是這樣的:
SELECT price_est.sau_price_avg
FROM price_est
WHERE
(price_est.county_id = _county_id OR price_est.county_id IS NULL) AND
(price_est.municipality_id = _municipality_id OR price_est.municipality_id IS NULL) AND
(price_est.district_id = _district_id OR price_est.district_id IS NULL) AND
(price_est.neighbourhood_id = _neighbourhood_id OR price_est.neighbourhood_id IS NULL)
ORDER BY price_est.neighbourhood_id NULLS LAST,
price_est.district_id NULLS LAST,
price_est.municipality_id NULLS LAST,
price_est.county_id NULLS LAST
LIMIT 1;