[英]Query Builder - whereRaw with subquery
I need to create the following query using Laravel Query Builder: 我需要使用Laravel查询生成器创建以下查询:
SELECT count(*) FROM table WHERE 1 < (SELECT count(*) FROM x WHERE y=2)
the question is - is it possible to do it using query builder? 问题是-是否可以使用查询生成器来做到这一点?
The only why I was able to achieve it is: 我能够实现这一目标的唯一原因是:
\DB::table('table')->whereRaw('1 < (SELECT count(*) FROM x WHERE y=2)')->count();
but this way I need to manually put here subquery and it's generating wrong query: 但是这种方式我需要手动将子查询放在这里,这会生成错误的查询:
SELECT count(*) FROM table WHERE 1 < (SELECT count(*) FROM x WHERE y=2) IS NULL
( is null
is added at the end) (在末尾添加is null
)
Is it possible to use here query builder also for subquery and make it to generate correct SQL? 是否可以在这里将查询生成器也用于子查询,并使其生成正确的SQL?
The only solution I found is creating separate query builder this way: 我发现的唯一解决方案是以这种方式创建单独的查询生成器:
$subQuery = \DB::table('x')->selectRaw('count(*)')->where('y',2);
\DB::table('table')->whereRaw('1 < ('.$subQuery->toSql().')')->addBinding($subQuery->getBindings());
尝试这个
\DB::table('table')->where(DB::raw('SELECT count(*) FROM x WHERE y=2'), '<',1)->count();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.