使用 Ecto 的相关子查询
Correlated subqueries using Ecto
您将如何在 Ecto
中编写相关子查询?
例如,SQL SELECT
查询的等价物是什么:
--Heaviest Lemmings per Group
SELECT ld.group_name, ld.id, ld.name, ld.weight
FROM lemming_data ld
WHERE weight = (
SELECT max(weight)
FROM lemming_data
WHERE group = ld.group_name
);
在 Ecto
语法中?我不确定如何引用外部查询的 group_name
.
在不使用片段的情况下,在 Ecto 中不可能进行相关子查询。所以它会是这样的:
from ld in "lemming_data",
where: ld.weight in fragment("(SELECT max(weight) FROM lemming_data WHERE group = ?)", ld.group_name),
select: ld # or {ld.group_name, ld.id, ld.name, ld.weight}
或:
from ld in "lemming_data",
where: fragment("? = (SELECT max(weight) FROM lemming_data WHERE group = ?)", ld.weight, ld.group_name),
select: ld # or {ld.group_name, ld.id, ld.name, ld.weight}
您将如何在 Ecto
中编写相关子查询?
例如,SQL SELECT
查询的等价物是什么:
--Heaviest Lemmings per Group
SELECT ld.group_name, ld.id, ld.name, ld.weight
FROM lemming_data ld
WHERE weight = (
SELECT max(weight)
FROM lemming_data
WHERE group = ld.group_name
);
在 Ecto
语法中?我不确定如何引用外部查询的 group_name
.
在不使用片段的情况下,在 Ecto 中不可能进行相关子查询。所以它会是这样的:
from ld in "lemming_data",
where: ld.weight in fragment("(SELECT max(weight) FROM lemming_data WHERE group = ?)", ld.group_name),
select: ld # or {ld.group_name, ld.id, ld.name, ld.weight}
或:
from ld in "lemming_data",
where: fragment("? = (SELECT max(weight) FROM lemming_data WHERE group = ?)", ld.weight, ld.group_name),
select: ld # or {ld.group_name, ld.id, ld.name, ld.weight}