您将如何在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
。
答案 0 :(得分:5)
在不使用片段的情况下,Ecto中无法进行相关的子查询。所以它会是这样的:
$results = select(
DB::raw("
pos_sales_code,
customer.customer_group,
customer_id,
customer.name,
customer.phone,
customer.email,
customer.referral_type AS referral,
pos_sales.created_at AS first_visit,
pos_sales_product.product_name
"))
->join(DB::raw('SELECT customer_id, Min(created_at) AS first_visit
FROM pos_sales
GROUP BY customer_id) X'), function($join){
$join->on('post_sales.customer_id', '=', 'first_visit'));
$join->on('post_sales.created_at', '=', 'first_visit'));
})
->leftJoin('customer', 'customer.id', '=', 'pos_sales.customer_id')
->leftJoin('post_sales_product', 'pos_sales.pos_sales_code', '=', 'pos_sales_product.pos_sales_code')
->get();
或:
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}