在Rails中,有一个有用的方法可以显示一个查询需要多长时间以及它是什么查询。
方法是“解释”。
所以我可以这样做:
User.where(name: 'Johnny').explain它将显示实际的sql查询。
'count‘方法也进行sql查询,但由于'count’返回一个数字,而不是活动记录,所以我不能对它使用explain。有没有办法做到这一点?
发布于 2016-01-16 01:04:23
这是可行的:
User.select('count(*)').where(name: 'Johnny').explain编辑:这确实是完全相同的:
irb(main):004:0> Benutzer.where(login: 'xxx').count
(2.2ms) SELECT COUNT(*) FROM "BENUTZER" WHERE "BENUTZER"."LOGIN" = 'xxx'
=> 0
irb(main):005:0> Benutzer.select("count(*)").where(login: 'xxx').explain
Benutzer Load (0.9ms) SELECT count(*) FROM "BENUTZER" WHERE "BENUTZER"."LOGIN" = 'xxx'
=> EXPLAIN for: SELECT count(*) FROM "BENUTZER" WHERE "BENUTZER"."LOGIN" = 'xxx'
Plan hash value: 1339361075
-------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
-------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 12 | 2 (0)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | 12 | | |
|* 2 | TABLE ACCESS FULL| BENUTZER | 1 | 12 | 2 (0)| 00:00:01 |
-------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter("BENUTZER"."LOGIN"='xxx')
Note
-----
- dynamic sampling used for this statement (level=2)https://stackoverflow.com/questions/34816137
复制相似问题