【发布时间】:2018-01-21 10:31:30
【问题描述】:
我在 Postgres 9.5 数据库中有以下表:
rate_adjust
Column | Type | Modifiers
-----------+---------+----------------------------------------------
id | integer | not null default nextval('product_days_id_seq'::regclass)
name | text |
amount | integer |
product_id | integer |
type | integer |
Indexes:
"pk_product_days" PRIMARY KEY, btree (id)
factor_calendar
Column | Type | Modifiers
----------------+-----------------------------+-----------------------------------------------------
id | integer | not null default nextval('product_id_seq'::regclass)
from_day | integer |
thru_day | integer |
created_at | timestamp without time zone | default now()
updated_at | timestamp without time zone | default now()
rate_adjust_id | integer |
Indexes:
"pk_product" PRIMARY KEY, btree (id)
Foreign-key constraints:
"fk_rate_adjust" FOREIGN KEY (rate_adjust_id) REFERENCES rate_adjust(id)
我需要获取rate_adjust 记录,这些记录要么在factor_calendar 表中没有foreign_key,要么如果它们的日期应该在from_day 和thru_day 范围内
我正在尝试使用以下查询,但也会返回不在该范围内的 rate_adjust 记录
SELECT *
FROM rate_adjust AS rad
LEFT JOIN factor_calendar as fc ON (
rad.id = fc.rate_adjust_id
WHERE rad.product_id = p_id
AND start_day_id < end_day_id AND NOT (
( fc.from_day > start_day_id AND fc.from_day > end_day_id)
OR ( fc.thru_day < start_day_id AND fc.thru_day < end_day_id)
)
factor_calendar中存储的数据是
id | from_day | thru_day | rate_adjust_id
—--+----------+----------+----------------
1 | 14 | 17 | 1
2 | 1 | 3 | 2
3 | 1 | 7 | 3
rate_adjust中存储的数据是
id | name | type | amount | product_id
—--+------------------------+------+------+------------—
1 | rateadjust 1 | 0 | 15 | 3
2 | rateadjust 2 | 0 | 15 | 3
3 | rateadjust 3 | 1 | 15 | 3
4 | rateadjust 4 | 1 | 22 | 3
对于上述query 和p_id = 3 和start_day_id = 4 和end_day_id = 15,我预计以下 rate_adjust 与
id(s) 1 和 2 和 4 被返回
但也返回了 id 3 的额定值
问题
如何修改我的查询以返回预期结果请考虑我也愿意接受任何建议以使用plpgsql 语言处理此问题
【问题讨论】:
-
鉴于您的解释,我不明白为什么会返回 id 2 和 3。另外,解释什么“日期应该在 from_day 和 thru_day 范围内”——这是模棱两可的。是整天的意思吗?一天?完全巧合?
标签: sql postgresql join