【问题标题】:How to turn this SQL query into an ActiveRecord query?如何将此 SQL 查询转换为 ActiveRecord 查询?
【发布时间】:2011-07-30 16:57:17
【问题描述】:

我有一个模型:Score player:string, sport:string score:integer

我目前正在为这个 SQL 查询使用 find_by_sql:

SELECT * FROM (SELECT * FROM scores ORDER BY score ASC) AS a1 GROUP BY a1.player HAVING a1.sport = 'Soccer';

为了可移植性,是否可以将上述 SQL 查询转换为 Rails ActiveRecord 查询?

谢谢

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:
    Score.group('player').having('sport = ?', 'Soccer').order('score')
    

    会生成SQL

    SELECT 'scores'.* FROM 'scores' GROUP BY player HAVING sport = 'Soccer' ORDER BY score 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      相关资源
      最近更新 更多