【问题标题】:Combine 2 results in one in SQL在 SQL 中将 2 个结果合二为一
【发布时间】:2018-11-27 17:14:16
【问题描述】:

更新合并

Cama::PostType.first.posts.joins(:custom_field_values)
.where("cama_custom_fields_relationships.custom_field_slug = ? AND 
cama_custom_fields_relationships.value LIKE ?","localization", 
"%Paris%").merge(Cama::PostType.first.posts.joins(:custom_field_values)
.where("cama_custom_fields_relationships.custom_field_slug = ? AND 
cama_custom_fields_relationships.value = ?","type-localization", "2"))

这也行不通。当单独执行时,它返回相同的 AssociationRelation。我猜它只适用于 ActiveRecord:Relation

更新 我想我正在寻找 INTERSECT 但不知道如何在 where 中使用它

我创建了另一个主题,但仍然找不到如何优化它的答案。

就是这样

我需要按“other_model”值查找“帖子”。其他模型与通过另一个表的帖子有关系,但让我们保持简单。当我这样做时

Foo.joins(:other_model).where("other_model.value = ? AND other_model.value = ?", "one", "two") 

这当然不会给我任何结果,因为它自相矛盾。

当我使用 OR 而不是 AND 时

Foo.joins(:other_model).where("other_model.value = ? OR other_model.value = ?", "one", "two") 

它会为我找到帖子,但是......它有一个值或者有第二个值并且......

我想根据 other_model.value = one 和 other_model.value = two 找帖子

这意味着它会查找 2 个单独的结果,然后我只需要返回相互覆盖的 id...这有意义吗?

【问题讨论】:

  • postgresql != mysql.此外,这看起来更像是某种包装库,而不是原始查询;标签中的此类信息通常很有帮助。
  • 主题不言自明。我想引起注意。我知道mysql!= postgresql。某些类型的查询在 mysql 中是可能的,而在 postgresql 中是不可能的,我在寻找任何答案时添加了两者,以及如何解决它的概念。
  • MySQL Postgres!!!这看起来不像两者中的任何一个。
  • 哦,没错。我正在寻找概念,它的红宝石
  • 您是否要查找具有 other_model 的值为“one”和另一个 other_model 的值为“two”的 foo?在原始 sql 中,您可以通过加入 other_models 两次来实现这一点。在我的脑海中,无法告诉如何在 activerecord 中执行此操作

标签: sql ruby-on-rails ruby


【解决方案1】:

我认为您正在寻找这样的查询:

Foo
  .joins(:other_model)
  .where('other_model.value = ? OR other_model.value = ?', 'one', 'two') 
  .group('foos.id')
  .having('COUNT(other_models.id) >= 2')

【讨论】:

  • HAVING。它与WHERE 基本相同,但在GROUP BY 之类的聚合函数之后运行。
  • 为什么要多或等于 2 ?我现在就去检查。谢谢你的回答
  • 因为你想找到所有至少有两个other_modelsfoos(一个有value == 'one'和一个有value == 'two'
  • 谢谢你,看来它成功了!但我需要对其进行测试以确定它是否真的有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-31
  • 2011-01-20
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多