gpt4 book ai didi

sql - rails 包含不同的值

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:02 24 4
gpt4 key购买 nike

我有一个标准的 ruby​​ 包含,smth。像那样:

  @properties = Property.where(id: property_ids)
.includes(:property_values).select('select distinct "property_values"."value"').references(:property_values)

我需要每个属性属性值的唯一值。

但是对于这个查询得到一个错误:

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

如何避免此错误并仅获取唯一属性值?

最佳答案

@properties = Property.where(id: property_ids)
.joins(:property_values).select('"property_values"."value"').distinct.references(:property_values)

请注意,我将 includes 更改为连接,因为 includes 在单独的查询中加载数据,而 join 实际上执行连接,允许您执行对查询中的数据执行操作..

我使用了 distinct 方法而不是将其放在 select 中,但是您可以这样做,但是您需要从字符串中删除 select 一词

@properties = Property.where(id: property_ids)
.joins(:property_values).select('distinct "property_values"."value"').references(:property_values)

阅读更多 http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html

关于sql - rails 包含不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23623633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com