Mysql ActiveRecord SQL语句未返回正确的数据
我的RubyonRails应用程序(Ruby2.1,Rails4.0.2)中的以下代码返回Mysql ActiveRecord SQL语句未返回正确的数据,mysql,ruby-on-rails,activerecord,Mysql,Ruby On Rails,Activerecord,我的RubyonRails应用程序(Ruby2.1,Rails4.0.2)中的以下代码返回 a = Order.select('if(currency1_id=3,unitprice,1/unitprice) as uu,sum(if(currency1_id=3,open_quantity,open_quantity*unitprice)) as qq').where("((currency1_id=? and currency2_id=? and otype = 0) or (otype =
a = Order.select('if(currency1_id=3,unitprice,1/unitprice) as uu,sum(if(currency1_id=3,open_quantity,open_quantity*unitprice)) as qq').where("((currency1_id=? and currency2_id=? and otype = 0) or (otype = 1 and currency1_id=? and currency2_id=?))",c1.id,c2.id,c2.id,c1.id).group('uu').order('uu desc').limit(20)
=> #<ActiveRecord::Relation [#<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, #<Order id: nil>, ...]>
这让我
=> "SELECT if(currency1_id=3,unitprice,1/unitprice) as uu,sum(if(currency1_id=3,open_quantity,open_quantity*unitprice)) as qq FROM `orders` WHERE (((currency1_id=3 and currency2_id=1 and otype = 0) or (otype = 1 and currency1_id=1 and currency2_id=3))) GROUP BY uu ORDER BY uu desc LIMIT 20"
我使用SQL语句并直接在MySQL中运行它,令我惊讶的是,与Rails不同,它完全返回了我期望它返回的数据
mysql> SELECT if(currency1_id=3,unitprice,1/unitprice) as uu,sum(if(currency1_id=3,open_quantity,open_quantity*unitprice)) as qq FROM `orders` WHERE (((currency1_id=3 and currency2_id=1 and otype = 0) or (otype = 1 and currency1_id=1 and currency2_id=3))) GROUP BY uu ORDER BY uu desc LIMIT 20;
+------------+----------------------+
| uu | qq |
+------------+----------------------+
| 0.02638201 | 0.2751620500000000 |
| 0.02638200 | 0.5000000000000000 |
| 0.02616701 | 13.7539900000000000 |
| 0.02616700 | 1.0000000000000000 |
| 0.02610030 | 0.3421014700000000 |
| 0.02610000 | 2.0000000000000000 |
| 0.02600000 | 10.1530000000000000 |
| 0.02597364 | 7.9000000000000000 |
| 0.02596814 | 0.2747080000000000 |
| 0.02591992 | 0.3999690000000000 |
| 0.02591991 | 1.9183083000000000 |
| 0.02591900 | 11.0000000000000000 |
| 0.02591002 | 90.0000000000000000 |
| 0.02591001 | 0.3667208155574714 |
| 0.02551036 | 1.0000000000000000 |
| 0.02550001 | 42.0000000000000000 |
| 0.02550000 | 108.0606277900000000 |
| 0.02540107 | 3.0000000000000000 |
| 0.02540000 | 0.0500000000000000 |
| 0.02520000 | 10.0000000000000000 |
+------------+----------------------+
20 rows in set (0.00 sec)
为什么ActiveRecord没有返回预期的结果?缺陷还是限制?ActiveRecord正是按照您的要求执行的。它从数据库中获取与使用SQL时相同的数据。唯一的区别是它如何返回它 在运行ActiveRecord查询后,请尝试以下操作
a.map {|order| [order.uu, order.qq] }
这将为您提供一个数组数组,表示SQL中的值
[[0.02638201, 0.2751620500000000],
[0.02638200, 0.5000000000000000],
[0.02616701, 13.7539900000000000],
.....]
ActiveRecord基本上返回一个只有uu和pp属性的订单数组。具体解释见文件
尝试a.to\u a不确定,但可能会有帮助a.to\u a返回的结果与完成的结果相同。
[[0.02638201, 0.2751620500000000],
[0.02638200, 0.5000000000000000],
[0.02616701, 13.7539900000000000],
.....]