Reputation: 351
I have 3 tables:
1. products(product_id,name)
2. orders(id,order_id,product_id)
3. factors(id,order_id,date)
I want to retrieve product names(products.name
) where have similar order_id
on a date
in two last tables.
I use this query for this purpose:
select products.name
from products
WHERE products.product_id ~IN
(
SELECT distinct orders.product_id FROM orders WHERE
order_id IN (select order_id FROM factors WHERE
factors.datex ='2017-04-29') GROUP BY product_id
)
but no result. where is my mistake? how can I resolve that? thanks
Upvotes: 2
Views: 67
Reputation: 1269513
Your query should be fine. I am rewriting it to make a few changes to the structure, but not the logic (this makes it easier for me to understand the query):
select p.name
from products p
where p.product_id in (select o.product_id
from orders o
where o.order_id in (select f.order_id
from factors f
where f.datex = '2017-04-29'
)
) ;
Notes on the changes:
SELECT DISTINCT
and GROUP BY
are unnecessary in IN
subqueries. The logic of IN
already handles (i.e. ignores) duplicates. And by explicitly including the operations, you run the risk of a less efficient query plan.Why might your query not work?
factors.datex
has a time component. If so, then this will work date(f.datex) = '2017-04-29'
.Upvotes: 2
Reputation: 628
In factors table column name is date so it should be -
factors.date ='2017-04-29'
You have written -
factors.datex ='2017-04-29'
Upvotes: 1