如何通过Ecto为MySQL提供索引提示

时间:2018-01-23 04:17:40

标签: mysql elixir ecto

我需要通过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中。如果可以的话,我想让片段尽可能小。

这只是一个临时解决方案。我们很快就会ANALYZE TABLES,所以这是不必要的。

1 个答案:

答案 0 :(得分:1)

目前不支持。请在Ecto存储库中打开一个问题,我们将对其进行讨论。谢谢!