我需要通过 Ecto 在左连接中提示 MySQL 的索引,这非常困难。
我得到的最接近的是:
query = from(s in Dossier.School,
left_join: sc in fragment("subscription_coordinators use index (subscription_coordinators_school_products_idx)"),
on: fragment("school_id = ?", 1)
and fragment("product in ('reading', 'maths')")
and is_nil(sc.deleted_at),
select: s,
where: s.id == 1
)
# Ecto.Adapters.SQL.to_sql(:all, Dossier.Repo, query)
query |> Dossier.Repo.all
在 IEx 中可以很好地编译并生成 SQL:
SELECT s0.`id`, s0.`name`, s0.`school_code`, s0.`deleted_at`, s0.`district_id`
FROM `schools` AS s0
LEFT OUTER JOIN (subscription_coordinators use index (subscription_coordinators_school_products_idx)) AS f1 ON (school_id = 1 AND product in ('reading', 'maths')) AND f1.`deleted_at` IS NULL WHERE (s0.`id` = 1)
但显然表别名的位置是错误的,因此实际运行查询会产生:
** (Mariaex.Error) (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'f1 ON (school_id = 1 AND product in ('reading', 'maths')) AND f1.`deleted_at` IS' at line 1
(ecto) lib/ecto/adapters/sql.ex:436: Ecto.Adapters.SQL.execute_and_cache/7
(ecto) lib/ecto/repo/queryable.ex:130: Ecto.Repo.Queryable.execute/5
(ecto) lib/ecto/repo/queryable.ex:35: Ecto.Repo.Queryable.all/4
完整的查询要大得多,有近十几个左连接(尽管这是唯一需要提示的)并且全部都在 Ecto 中。如果可以的话,我希望片段尽可能小。
但这只是一个临时解决方案。我们很快就会分析表格
,因此没有必要。
最佳答案
目前不支持。请在 Ecto 存储库中提出问题,我们将进行讨论。谢谢!
关于mysql - 如何通过 Ecto 向 MySQL 提供索引提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48394148/