我有一个标准的ruby includes,smth。就像这样
@properties = Property.where(id: property_ids)
.includes(:property_values).select('select distinct "property_values"."value"').references(:property_values)
我需要每个属性值的uniq值。
但是对于这个查询得到一个错误:
PG::SyntaxError - ERROR: syntax error at or near "select"
LINE 1: ...S t1_r4, "property_values"."updated_at" AS t1_r5, select dis...
以下是完整的查询:
: SELECT "properties"."id" AS t0_r0, "properties"."k1c" AS t0_r1, "properties"."name" AS t0_r2, "properties"."created_at" AS t0_r3, "properties"."updated_at" AS t0_r4, "property_values"."id" AS t1_r0, "property_values"."value" AS t1_r1, "property_values"."product_id" AS t1_r2, "property_values"."property_id" AS t1_r3, "property_values"."created_at" AS t1_r4, "property_values"."updated_at" AS t1_r5, select distinct "property_values"."value" FROM "properties" LEFT OUTER JOIN "property_values" ON "property_values"."property_id" = "properties"."id" WHERE "properties"."id" IN (159, 27, 26, 25, 24, 23, 22, 4, 1) AND "properties"."id" IN (1) ORDER BY "properties"."id" ASC
我如何避免这个错误并只得到uniq属性值?
1条答案
按热度按时间9udxz4iz1#
注意,我将
includes
更改为join,因为includes
在单独的查询中加载数据,而join
实际上执行join,允许您对查询中的数据执行操作。我使用了distinct方法,而不是将其放在select中,但是您可以这样做,但您需要从字符串中删除select一词
阅读更多http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html