我有这样的ActiveRecord查询。这段代码没有问题。
order(<<-SQL)
CASE WHEN MAX(disclosures.filed_at) > MAX(short_positions.published_on)
THEN MAX(disclosures.filed_at)
ELSE MAX(short_positions.published_on)
END
SQL
我认为如果用if语句写它会更简单。
order(<<-SQL)
IF (MAX(disclosures.filed_at) > MAX(short_positions.published_on))
THEN MAX(disclosures.filed_at)
ELSE MAX(short_positions.published_on)
END IF
SQL
但它失败并出现错误:
PG::SyntaxError: ERROR: syntax error at or near "MAX" LINE 1: ... 1) GROUP BY companies.id ORDER BY IF MAX(disclo.
我做错了什么?
"SELECT companies.* FROM \"companies\" INNER JOIN \"stocks\" ON \"stocks\".\"company_id\" = \"companies\".\"id\" INNER JOIN \"disclosures\" ON \"disclosures\".\"company_id\" = \"companies\".\"id\" INNER JOIN \"short_positions\" ON \"short_positions\".\"company_id\" = \"companies\".\"id\" WHERE (stocks.user_id = 1) GROUP BY companies.id ORDER BY IF MAX(disclosures.filed_at) > MAX(short_positions.published_on)\n THEN MAX(disclosures.filed_at)\n ELSE MAX(short_positions.published_on)\n END IF\n"
答案 0 :(得分:2)
应该有THEN
个关键字..
order(<<-SQL)
IF (MAX(disclosures.filed_at) > MAX(short_positions.published_on)) THEN
MAX(disclosures.filed_at)
ELSE
MAX(short_positions.published_on)
END IF
SQL