2017-09-07 17 views
0

laravelにsqlクエリを渡そうとしていますが、このクエリではテーブルが複合プライマリキーを使用して結合されています。 SQLコードがlaravelサブクエリの選択、複合プライマリキーのテーブル

  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句が異なるテーブル、行うにはどのように任意のアイデアで同じ条件を、それを持っていますこれはラヴェルで?

答えて

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(); 
関連する問題