sql - 使用 select 从不同的表中获取列值

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

我对我的交互器有这个查询:

 Variant.where(code: context.codes)
        .joins("LEFT OUTER JOIN prices p
                ON p.variant_id = variants.id")
        .select("code,
                 actual_price,
                 selling_price,
                 p.cost")

返回:

#<Interactor::Context codes=["PRDCTA-V1", "PRDCTA-V2"], body=[#<Variant id: nil, selling_price: nil, code: "PRDCTA-V2", actual_price: nil>,
#<Variant id: nil, selling_price: #<BigDecimal:7ff1d13b9118,'0.1E3',9(18)>, code: "PRDCTA-V1", actual_price: nil>]

我不知道为什么 prices 表中的 p.cost 没有出现,这意味着我的选择是错误的。我试过改成costprices.cost还是不行。

我的预期输出应该是

[#<Variant id: nil, selling_price: nil, code: "PRDCTA-V2", actual_price: nil, cost:{value here}>,

最佳答案

试试这个,在选择中为成本分配一个别名

p.cost AS price_cost

然后,通过variants.first.price_cost获取它

或者,只需从 attributes

获取它
variants.first.attributes['cost']

会返还费用。

希望对您有所帮助!

关于sql - 使用 select 从不同的表中获取列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637986/

相关文章:

ruby - 循环遍历整数中的位,ruby

ruby - 使用 ruby​​ 优化时出现 NoMethodError

sql - Rails 动态 'Where' 子句

sql - Postgres - 这是在 bool 列上创建部分索引的正确方法吗?

java - JOOQ 生成器 : Missing name

python - Django JSONField isnull 查找

php - 如何在sql中按周对数据进行分组?

sql - 选择艺术家专辑列表并显示每个专辑中已请求艺术家和专辑的轨道数

sql - 使用计数表选择重复日期的查询

mysql - LIKE 运算符无法正常处理日期