简体   繁体   English

链接将表连接到导轨

[英]Chaining joins tables in rails

I'm trying to join multiple tables together and then make a query but I'm running into a syntax error. 我试图将多个表连接在一起,然后进行查询,但是遇到语法错误。

I have the following tables: 我有以下表格:

achievement_standards
  id
  description

terms
  start_date
  end_date
  term_year_id

term_standards
  term_id
  achievement_standard_id

And I have the following method: 我有以下方法:

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")
  .where("term_standards.id IS ? OR (term_standards.term_id IS NOT ? AND terms.term_year_id IS NOT ?)", nil, nil, 100),

end

I'm getting a syntax error at or near "100" . syntax error at or near "100"出现syntax error at or near "100" Is there something wrong with how I joined the tables? 我如何参加餐桌有问题吗? I'm trying to get achievement standards that are not in the term_standards table or ones that are not in the term_year 100. 我正在尝试获取不在term_standards表中或不在term_year 100中的成就标准。

The last part of your query : 查询的最后一部分:

... AND terms.term_year_id IS NOT ?

When given param 100 , this will expand as : 给定参数100 ,它将扩展为:

... AND terms.term_year_id IS NOT 100

This is not valid SQL : IS is not to compare a value with a number, for this you would need to use the (in)equality operator. 这是无效的SQL: IS不能将值与数字进行比较,因此您需要使用(in)等于运算符。 You probably want : 您可能想要:

... AND terms.term_year_id <> ?

More generally speaking : in most RDBMS, IS is only used in conjonction with NULL (either IS NULL , or IS NOT NULL ). 更笼统地说:在大多数RDBMS中, IS仅与NULLIS NULLIS NOT NULL )结合使用。 So basically this type of parameterized expressions can only be used with a NULL parameter (that is, the RDBMS will raise an error if passed another value) : 因此,基本上,这种类型的参数化表达式只能与NULL参数一起使用(即,如果传递另一个值,则RDBMS将引发错误):

term_standards.id IS ?
term_standards.term_id IS NOT ?

Depending on your purpose, either you don't need to use parameters (make the ? explicitly NULL in your query), or you might want to refactor your query. 根据您的目的,或者您不需要使用参数(在查询中将?显式设置为NULL ),或者您可能想重构查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM