【发布时间】:2018-06-10 12:29:54
【问题描述】:
我在 Postgres 9.5 数据库中有以下表:
product_days
Column | Type | Modifiers
-----------+---------+----------------------------------------------
id | integer | not null default nextval('product_days_id_seq'::regclass)
days_id | integer |
product_id | integer |
available | integer |
price | integer |
Indexes:
"pk_product_days" PRIMARY KEY, btree (id)
"idx_product_days" btree (days_id)
"idx_product_days_0" btree (product_id)
Foreign-key constraints:
"product_days_days_id_fkey" FOREIGN KEY (days_id) REFERENCES days(id)
product
Column | Type | Modifiers
----------------+-----------------------------+-----------------------------------------------------
id | integer | not null default nextval('product_id_seq'::regclass)
name | character varying(100) |
number_of_items | integer |
created_at | timestamp without time zone | default now()
updated_at | timestamp without time zone | default now()
total_number | integer |
Indexes:
"pk_product" PRIMARY KEY, btree (id)
product_days.product_id 是引用product 表的外键,available 表示每天可用的产品数量。
我想获得在某些特定日期 (days_id between 5 and 10) 可用的所有产品 (available > 0)。这些天所有都应该可以使用它们。
目前我正在尝试使用以下查询获取结果,但我不确定它是否正确或者这是最有效的方法:
select product.id as p_id, product.name as p_name, product.number_of_items as items
from product_days join product ON product_days.product_id = product.id
WHERE product_days.available > 0
AND prodcut_days.days_id between 5 and 10
group by product.id
HAVING count(*) > 5;
输出应该是这样的:
p_id | p_name | items
-------+-----------+-------
1 | product_1 | 4
2 | product_2 | 13
我需要在 SQL 或 plpgsql 中运行此查询的最有效方式。
【问题讨论】:
-
请发布一些示例数据的预期输出
-
@RadimBača 我刚刚编辑了问题,请再次检查
-
我错过了样本数据
-
缺少:表定义(显示数据类型和约束)、Postgres 版本、示例数据和您迄今为止尝试过的查询(即使它不起作用)。我想你的意思是你提到“pgpsql”的地方?
-
@ErwinBrandstetter 我已经编辑了这个问题,请您再次检查一下,看看现在是否提供了足够的信息
标签: sql postgresql postgresql-performance relational-division