我想要理解在Repo.preload执行的查询中,为什么会有order by子句。
App.Repo.get(Sopitas.Continent, 1) |> App.Repo.preload(:countries)执行的查询包括:
[debug] QUERY OK source="continents" db=0.4ms
SELECT c0.`id`, c0.`name`, c0.`sm_id`, c0.`inserted_at`, c0.`updated_at`
FROM `continents` AS c0 WHERE (c0.`id` = ?) [1]
[debug] QUERY OK source="countries" db=3.5ms decode=1.1ms
SELECT c0.`id`, c0.`sm_id`, c0.`name`, c0.`continent_id`, c0.`inserted_at`, c0.`updated_at`, c0.`continent_id`
FROM `countries` AS c0 WHERE (c0.`continent_id` = ?)
ORDER BY c0.`continent_id` [1]我之所以想理解这一部分,是因为据我所知,order by子句为查询的执行增加了处理时间。我更倾向于避免order by。
发布于 2017-10-25 13:01:30
这并不是因为Repo.preload,而是因为这个preload查询返回了很多记录。
ORDER BY子句为added by Ecto,用于在获取大量记录之前有效地对国家/地区进行分组(在DB引擎内)。
我提供的链接显示了一种通用的Ecto方法:一旦查询要返回许多记录,它就会按键对这些记录进行排序。
发布于 2017-10-25 15:43:28
在构造查询片段时,也可以将SQL子句函数与预加载一起使用。例如:
alias App.Repo
Sopitas.Continent
|> Repo.get(1)
|> Repo.preload([countries: (from c in Country, order_by: c.<your_field_goes_here>)])学习官方docs真的很好;)
https://stackoverflow.com/questions/46922406
复制相似问题