我有以下SQL从嵌套表中提取根节点(相对于用户,即分配给用户的最高节点),
SELECT
child_domain.*, child_subscription.user_id
FROM
domains AS child_domain
JOIN subscriptions
AS child_subscription
ON child_subscription.domain_id = child_domain.id
WHERE NOT EXISTS
(
SELECT 1
FROM domains AS parent_domain
JOIN subscriptions
AS parent_subscription
ON parent_subscription.domain_id = parent_domain.id
WHERE
parent_domain.start < child_domain.start
AND
parent_domain.end > child_domain.end
AND
parent_subscription.user_id = child_subscription.user_id
);
上面返回嵌套行的根节点,表格看起来像这样,
----------- ----------------- ---------
| DOMAINS | | SUBSCRIPTIONS | | USERS |
----------- ----------------- ---------
| id | | user_id | | id |
| start | | domains_id | | name |
| end | ----------------- ---------
-----------
但是,我在将其转换为Eloquent时遇到了麻烦。问题似乎出现在子查询中(我已尝试过whereDoesntHave
和whereNotExists
,但都没有工作)。
DB::table('domains as child_domain')
->join('subscriptions as child_subscription','child_subscription.domain_id','child_domain.id')
->whereNotExists('domains as parent_domain',function($query){
$query
->join('subscriptions as parent_subscription','parent_subscription.domain_id','parent_domain.id')
->where('parent_domain.end','>','parent_domain.end')
->where('parent_domain.start'.'<','parent_domain.start')
->where('parent_subscription.user_id', 'child_subscription.user_id')->get();
});
上面的代码,当我输出toSql()
节目时,
select * from `domains` as `child_domain` inner join `subscriptions` as `child_subscription` on `child_subscription`.`domain_id` = `child_domain`.`id` where not exists (select *)
任何帮助表示感谢。
答案 0 :(得分:0)
经过测试并准确生成您想要的内容。
DB::table('domains as child_domain')
->join('subscriptions as child_subscription', 'child_subscription.domain_id', 'child_domain.id')
->whereNotExists(function($query) {
$query->selectRaw(1)
->from('domains as parent_domain')
->join('subscriptions as parent_subscription', 'parent_subscription.domain_id', 'parent_domain.id')
->whereColumn('parent_domain.start', '<', 'child_domain.start')
->whereColumn('parent_domain.end', '>', 'child_domain.end')
->whereColumn('parent_subscription.user_id', 'child_subscription.user_id');
})
->select('child_domain.*', 'child_subscription.user_id')
->get();
查询精心设计
select `child_domain`.*, `child_subscription`.`user_id` from `domains` as `child_domain` inner join `subscriptions` as `child_subscription` on `child_subscription`.`domain_id` = `child_domain`.`id` where not exists (select 1 from `domains` as `parent_domain` inner join `subscriptions` as `parent_subscription` on `parent_subscription`.`domain_id` = `parent_domain`.`id` where `parent_domain`.`start` < `child_domain`.`start` and `parent_domain`.`end` > `child_domain`.`end` and `parent_subscription`.`user_id` = `child_subscription`.`user_id`)