我的数据库中有地址和定价数据。定价数据不完整,通常适用于某个地区,其他时间适用于特定地址。我有一个plpgsql函数,可以检索最准确的定价数据。我目前在我的功能中有这个:
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;
...
如果某处的数据不可用,则该区域没有外键引用。
这对我来说似乎是一个非常笨拙的解决方案。有更好的方法吗?
我可以对表进行更改并且数据显示是必要的。
----------------------------------- edit ----------- ------------------------
我让尼克巴恩斯的回答对我来说是这样的:
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;
答案 0 :(得分:2)
您可以同时选择它们,并使用ORDER BY
/ LIMIT
按照准确性排列优先顺序:
SELECT price_est.sau_price_avg
INTO _est_price
FROM price_est
WHERE
(price_est.neighbourhood_id = _neighbourhood_id OR price_est.neighbourhood_id IS NULL) AND
price_est.district_id = _district_id AND
price_est.municipality_id = _municipality_id AND
price_est.county_id = _county_id
ORDER BY price_est.neighbourhood_id NULLS LAST
LIMIT 1;
请注意,NULLS LAST
是默认排序,因此并非绝对必要,但在这种情况下明确表达您的意图是件好事。