Answer the question
In order to leave comments, you need to log in
What is wrong in a PostgreSQL query?
there is a query like this where:
2 = car make
129 = mercedes
19 = steering wheel
2001569 = right side
20 = fuel
2001570 = diesel, 2001571 = gasoline
and it selects all Mercedes, all right hand drive, and all diesel cars and all cars on gasoline
, the problem is that it should select only Mercedes with a right-hand drive and with diesel and gasoline,
the query is greatly simplified
if you can explain what I am writing wrong
here is the table structure of
the SQL query:
SELECT *
FROM products p
WHERE p.id IN
(SELECT DISTINCT pc.product_id
FROM product_characteristic pc
WHERE pc.product_id = p.id
AND pc.characteristic_id IN (2, 19, 20)
AND pc.selected_option_id IN (129, 2001569, 2001570, 2001571)
)
Answer the question
In order to leave comments, you need to log in
SELECT *
FROM products p
WHERE EXISTS(SELECT 'x' FROM product_characteristic pc WHERE pc.characteristic_id = 2 AND pc.selected_option_id = 129 AND pc.product_id=p.id)
AND EXISTS(<второй фильтр>)
AND EXISTS(<третий фильтр>)
"In his personal file it was written - SPECIAL SIGNS - everything" (Dellamorte Dellamore)
1) It seems to me that you should seriously rework the structure of the database
2) Let's rephrase your request:
SELECT *
FROM products p
WHERE p.id IN
(SELECT DISTINCT pc.product_id
FROM product_characteristic pc
WHERE pc.product_id = p.id
AND pc.characteristic_id= ANY (2, 19, 20)
AND pc.selected_option_id=ANY (129, 2001569, 2001570, 2001571)
)
SELECT *
FROM products p
WHERE p.id IN
(SELECT DISTINCT pc.product_id
FROM product_characteristic pc
WHERE pc.product_id = p.id
AND (pc.characteristic_id =2 OR pc.characteristic_id =19 or pc.characteristic_id =20)
AND (pc.selected_option=129 OR pc.selected_option=2001569 OR pc.selected_option=2001570 or pc.selected_option=2001571)
)
SELECT *
FROM products p
WHERE p.id IN
(SELECT pc.product_id
FROM product_characteristic pc, product_characteristic pc1,product_characteristic pc2,
WHERE pc.product_id=pc1.product_id and pc.product_id=pc2.product_id
AND pc.characteristic=2 AND pc.selected_option_id=129
AND pc1.characteristic=19 AND pc1.selected_option_id=2001569
AND pc2.characteristic=20 AND pc2.selected_option_id in (2001570, 2001571)
)
SELECT *
FROM products p
WHERE p.id IN
(SELECT pc.product_id
FROM product_characteristic pc, product_characteristic pc1,product_characteristic pc2,
WHERE pc.product_id=pc1.product_id and pc.product_id=pc2.product_id
AND pc.selected_option_id=129
AND pc1.selected_option_id=2001569
AND pc2.selected_option_id in (2001570, 2001571)
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question