我正在使用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)
但这不会选择任何产品记录。
答案 0 :(得分:1)
它不生成任何记录,因为没有符合这两个标准的custom_field_answers
记录。你想要的是一张在表格中有必要记录的product_id
列表。为了防止没有人为你编写SQL,直到我有机会自己解决这个问题,我想我至少会向你解释为什么你的查询无效。
答案 1 :(得分:1)
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
答案 2 :(得分:0)
这应该有效:
SELECT p。* FROM products LEFT JOIN custom_field_answers c ON(c.product_id = p.id AND c.value LIKE'%bangle%'AND c.number_value希望有所帮助
答案 3 :(得分:0)
与手镯相关的number_value字段为空,因此在这些情况下您将无法进行直接比较。相反,首先将空值转换为0。
SELECT "products".* FROM "products" INNER JOIN "custom_field_answers"
ON "custom_field_answers"."product_id" = "products"."id"
WHERE ("custom_field_answers"."value" LIKE '%bangle%')
AND (coalesce("custom_field_answers"."number_value", 0) < 50)
答案 4 :(得分:0)
实际上没有测试它,但这个一般的想法应该有效:
SELECT *
FROM products
WHERE
EXISTS (
SELECT *
FROM custom_field_answers
WHERE
custom_field_answers.product_id = products.id
AND value = 'bangle'
)
AND EXISTS (
SELECT *
FROM custom_field_answers
WHERE
custom_field_answers.product_id = products.id
AND number_value < 5
)
用简单的英语:获取所有产品......
custom_field_answers
中有value = 'bangle'
custom_field_answers
number_value < 5
。