create table(:cms_changelog_categories) do
add :title, :string
end
create table(:cms_changelog_records) do
add :name, :string
add :category_id, :id
end
iex(1)> import Ecto.Query
Ecto.Query
iex(2)> alias Squery.{Repo}
[Squery.Repo]
iex(3)> Repo.insert_all("cms_changelog_categories",[
...(3)> [title: "First"],
...(3)> [title: "Second"],
...(3)> [title: "Third"]
...(3)> ])
12:15:59.835 [debug] QUERY OK db=7.7ms
INSERT INTO "cms_changelog_categories" ("title") VALUES ($1),($2),($3) ["First", "Second", "Third"]
{3, nil}
iex(4)> Repo.insert_all("cms_changelog_records",[
...(4)> [name: "One", category_id: 1],
...(4)> [name: "Two", category_id: 2],
...(4)> [name: "Two", category_id: 2],
...(4)> [name: "Three", category_id: 3],
...(4)> [name: "Three", category_id: 3],
...(4)> [name: "Three", category_id: 3]
...(4)> ])
12:16:15.459 [debug] QUERY OK db=8.4ms
INSERT INTO "cms_changelog_records" ("category_id","name") VALUES ($1,$2),($3,$4),($5,$6),($7,$8),($9,$10),($11,$12) [1, "One", 2, "Two", 2, "Two", 3, "Three", 3, "Three", 3, "Three"]
{6, nil}
iex(5)> sub = from(c in "cms_changelog_records",
...(5)> group_by: c.category_id,
...(5)> select: %{category_id: c.category_id, record_count: count(c.id)})
#Ecto.Query<from c in "cms_changelog_records", group_by: [c.category_id],
select: %{category_id: c.category_id, record_count: count(c.id)}>
iex(6)> query = from(d in "cms_changelog_categories",
...(6)> join: e in subquery(sub), on: d.id == e.category_id,
...(6)> select: %{title: d.title, record_count: e.record_count})
#Ecto.Query<from c0 in "cms_changelog_categories",
join: c1 in subquery(from c in "cms_changelog_records",
group_by: [c.category_id],
select: %{category_id: c.category_id, record_count: count(c.id)}),
on: c0.id == c1.category_id,
select: %{title: c0.title, record_count: c1.record_count}>
iex(7)> Repo.all(query)
12:16:44.436 [debug] QUERY OK source="cms_changelog_categories" db=1.7ms
SELECT c0."title", s1."record_count" FROM "cms_changelog_categories" AS c0 INNER JOIN (SELECT c0."category_id" AS "category_id", count(c0."id") AS "record_count" FROM "cms_changelog_records" AS c0 GROUP BY c0."category_id") AS s1 ON c0."id" = s1."category_id" []
[
%{record_count: 1, title: "First"},
%{record_count: 2, title: "Second"},
%{record_count: 3, title: "Third"}
]
iex(8)>