admin

如何查找具有特定多属性值的所有产品

sql

我正在使用postgresql。

我有一个名为custom_field_answers的表。数据看起来像这样

Id | product_id | value      | number_value | 
4  | 2          |            | 117          |
3  | 1          |            | 107          |
2  | 1          | bangle     |              |
1  | 2          | necklace   |              |

我想查找所有text_value为“ bangle”且number_value小于50的产品。

这是我的第一次尝试。

SELECT "products".* FROM "products" INNER JOIN "custom_field_answers" 
ON "custom_field_answers"."product_id" = "products"."id" 
WHERE ("custom_field_answers"."value" ILIKE 'bangle')

这是我的第二次尝试。

 SELECT "products".* FROM "products" INNER JOIN "custom_field_answers" 
ON "custom_field_answers"."product_id" = "products"."id" 
where ("custom_field_answers"."number_value" < 50)

这是我最后的尝试。

SELECT "products".* FROM "products" INNER JOIN "custom_field_answers" 
ON "custom_field_answers"."product_id" = "products"."id" 
WHERE ("custom_field_answers"."value" ILIKE 'bangle') 
AND ("custom_field_answers"."number_value" < 50)

但这不会选择任何产品记录。


阅读 150

收藏
2021-07-01

共1个答案

admin

WHERE子句一次只能查看一行中的列。

因此,如果您需要一个条件应用于表中的两个 不同 行,则需要两次连接到该表,以便可以从这两个行中获取列。

SELECT p.*
FROM "products" AS p
INNER JOIN "custom_field_answers" AS a1 ON p."id" = a1."product_id"
INNER JOIN "custom_field_answers" AS a2 ON p."id" = a1."product_id" 
WHERE a1."value" = 'bangle' AND a2."number_value" < 50
2021-07-01