我正在尝试将sql查询传递给laravel,但在此查询中,表使用复合主键连接,另外它还有这些表的子查询,因此我不知道如何操作
sql代码如下所示
select distinct g.id,
(
select count(*) from xxx s(nolock) inner join yyy t(nolock)
on t.id=s.id
and t.year=s.year
and t.code=s.code
where s.year = 2017
and t.status<>'C'
and s.created_at>=convert(datetime,'16/08/2017 00:00:00',103)
and s.created_at<=convert(datetime,'22/08/2017 23:59:59',103)
and s.id=g.id
) as xxx,
(
select count(*) from zzz s(nolock) inner join yyy t(nolock)
on t.id=s.id
and t.year=s.year
and t.code=s.code
where s.year = 2017
and t.status<>'C'
and s.created_at>=convert(datetime,'16/08/2017 00:00:00',103)
and s.created_at<=convert(datetime,'22/08/2017 23:59:59',103)
and s.id=g.id
) as zzz
from globals g(nolock) order by g.id
它有很多这样的子查询我放在这里,在连接中的条件相同,where where子句但是不同的表,不知道怎么在laravel中这样做?
答案 0 :(得分:0)
可以在Laravel中使用原始查询。
DB::select('select * from users where active = ?', [1]);
在这里阅读更多相关信息 https://laravel.com/docs/5.4/database#running-queries
答案 1 :(得分:0)
解决:3,我不敢相信这很容易,我试过这个并且它有效。谢谢你的帮助,很抱歉打扰你。 :$
$data = \DB::table("globals")
->select("globals.id",
\DB::raw("(select count(*) from xxx s(nolock) inner join yyy t(nolock)
on t.id=s.id
and t.year=s.year
and t.code=s.code
where s.year = 2017
and t.status<>'C'
and s.created_at>=convert(datetime,'16/08/2017 00:00:00',103)
and s.created_at<=convert(datetime,'22/08/2017 23:59:59',103)
and s.id=globals.id
) as xxx
"),
\DB::raw("(select count(*) from zzz s(nolock) inner join yyy t(nolock)
on t.id=s.id
and t.year=s.year
and t.code=s.code
where s.year = 2017
and t.status<>'C'
and s.created_at>=convert(datetime,'16/08/2017 00:00:00',103)
and s.created_at<=convert(datetime,'22/08/2017 23:59:59',103)
and s.id=globals.id
) as zzz
")
)
->orderBy('globals.id', 'asc')
->get();