加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 使用相同名称的列连接表上的Rails“.pluck”返回一个值,

发布时间:2020-12-12 06:27:17 所属栏目:MsSql教程 来源:网络整理
导读:Experiment has_many :features Feature belongs_to :experimentExperiment.where("experiments.id=1") .joins(:features) .pluck("features.id","experiments.id") 我希望这会返回每个功能的ID和实验的ID. [ [1,1],[2,[3,# ....] 相反,这将返回实验的ID,然
Experiment has_many :features 
Feature belongs_to :experiment

Experiment.where("experiments.id=1")
    .joins(:features)
    .pluck("features.id","experiments.id")

我希望这会返回每个功能的ID和实验的ID.

[
    [1,1],[2,[3,# ....
]

相反,这将返回实验的ID,然后返回nil

[
    [1,nil],[1,# ....
]

这有三个方面很奇怪:

>即使它是一个内连接,只返回一个实验,我能够从功能中提取列(features.name)
>一切都很好,直到重复列名称.
>首先报告最后一个弹出列,就好像第一列被覆盖一样.切换拔除顺序会切换返回值.

这似乎是一个错误,但也许我做错了什么.有小费吗?

SQL输出:

SELECT features.id,experiments.id FROM "experiments" INNER JOIN "features" ON "features"."experiment_id" = "experiments"."id" WHERE (experiments.id=1)

注意.这是一个与查询类似的简化问题:

Experiment.where("experiments.id=1")
    .joins(feature: { child2: { :child3 } })
    .pluck("feature.id,child3.id")

解决方法

这有点棘手.由于存在INNER JOIN,因此查询在此实例中仅生成一个id.实际上你可以反过来形成查询:
Feature.joins(:experiment)
       .where(features: { experiment_id: 1 })
       .pluck(:id,:experiment_id)

要么:

Feature.joins(:experiment)
       .where(experiments: { id: 1 })
       .pluck(:id,:experiment_id)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读