I have the following tables in a Postgres 9.5 database:
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
is a foreign key referring to the product
table and available
represents the number of products available in each day.
I want to get all products that are available (available > 0
) at some specific days (days_id between 5 and 10
). They should be available at all of these days.
Currently I am trying to get the result with the following query but I am not sure whether it is correct or this is the most efficient way to do it:
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;
The output should be like:
p_id | p_name | items
-------+-----------+-------
1 | product_1 | 4
2 | product_2 | 13
I need the most efficient way of running this query either in SQL or in plpgsql.