Laravel joinSub的使用,你也知道嗎?

chowjiawei發表於2021-10-21

我有個語句,想著以為 join 子查詢不支援改成模型查詢的寫法呢,百度了下,發現有 joinSub 的語法,在下孤陋寡聞了,特此記錄

以下語句目的是,取全表最新日期的那條(相同欄位中有重複時,只取最新)
表欄位大寫不是我定的~我只是查詢使用者

        $resultIds = DB::connection('fund')->select("
SELECT
 t1.InvestAdvisorCode
FROM
 table t1
 INNER JOIN ( SELECT SUBSTRING_INDEX( group_concat( id ORDER BY EndDate DESC ), ',', 1 ) AS id FROM table t2 GROUP BY InvestAdvisorCode ) t2 ON t1.id = t2.id
order by t1.TotalFundNV desc
");
      $subQuery = Table::query()
            ->selectRaw("SUBSTRING_INDEX( group_concat( id ORDER BY EndDate DESC ), ',', 1 ) AS id")
            ->from('table as t2')
            ->groupBy('InvestAdvisorCode')
            ->getQuery();

        $resultIds=Table::query()
            ->from('table as t1')
            ->joinSub($subQuery,'t2','t1.id','=','t2.id')
            ->orderBy('t1.TotalFundNV','desc')
            ->pluck('InvestAdvisorCode')->toArray()
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章