sql - rails 包含不同的值

标签 sql ruby-on-rails ruby postgresql ruby-on-rails-4

我有一个标准的 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/

相关文章:

javascript - 形成 Angular Action

ruby-on-rails - 月/日的慢性解析

MySQL 临时表存在 Case 语句问题

mysql 查询 - 一起使用 in & order by 和 limit

ruby-on-rails - 如何遍历图像数组并使用 Active Storage 保存每个图像?

ruby-on-rails - 使用 Rails 和 nokogiri 解析 html

html - 没有 .html 扩展名的链接,无需创建目录

ruby-on-rails - 在多用户 saas 应用程序中生成序列号

php - 从 mysql 中的一对多连接中提取最新结果

mysql - 如何在 MySQL 的 SET 子句中使用 SELECT 子句?