返回连接表的不同/唯一记录

时间:2019-01-25 00:37:52

标签: sql ruby-on-rails

我已经加入了多个表来构造我的记录,如下所示,但是现在我想返回未分配给term_year_id 301的唯一标准(即,我想返回standard_id 1 and 4)。

id   standard_id   term_id     term_year_id
 1        1          200            300
 2        2          200            300
 3        2          201            301
 4        3          202            300

我尝试返回不等于term_year_id 301的记录,但会返回我不想要的standard 2。我也尝试过分组/共享,但是语法错误?

def school_standards
  @standards = @school.achievement_standards
  .joins("LEFT OUTER JOIN term_standards ON achievement_standards.id = term_standards.achievement_standard_id")
  .joins("LEFT OUTER JOIN terms ON terms.id = term_standards.term_id")
  .group("terms.term_year_id")
  .having("terms.term_year_id <> 301)

end

什么是正确的方法?我在postgres中使用了rails。

2 个答案:

答案 0 :(得分:0)

似乎您可以得到一个唯一的standard_id列表,其中term_year_id等于301,然后将它们踢出去。像下面这样的东西应该起作用:

select a.*
from myTable a
where standard_id not in (select distinct standard_id from myTable where term_year_id = 301)

答案 1 :(得分:0)

给出上表以及表'Stt'(标准术语Term_year)的模型

  def test_the_ticket
    rows = [
      {standard_id: 1, term_id: 200, term_year_id: 300},
      {standard_id: 2, term_id: 200, term_year_id: 300},
      {standard_id: 2, term_id: 201, term_year_id: 301},
      {standard_id: 3, term_id: 202, term_year_id: 300}
    ]
    Stt.create! rows
    results = Stt.select(:standard_id, 'array_agg(term_year_id) as term_year_ids').group('standard_id').having('NOT array_agg(term_year_id) @> Array[301]')
    assert_equal([1,3], results.map(&:standard_id))
  end

也许有更好/更漂亮的方法,但是会做到的。

  Stt Load (1.8ms)  SELECT "stts"."standard_id", array_agg(term_year_id) as term_year_ids FROM "stts" GROUP BY "stts"."standard_id" HAVING (NOT array_agg(term_year_id) @> Array[301])