我试图在gift_code表中获取每个广告系列的唯一批次数。 gift_code表通过campaign_id连接到广告系列表。
Here is some sample data for campaign table. --------------+-------------- |campaign_id | name | --------------+-------------- | 1 | abc | --------------+-------------- | 2 | xyz | --------------+-------------- Below is some sample data for gift_code table. --------------+------------------------+--------------+ |gift_code_id | campaign_id | batch | unique_code | --------------+-------------+----------+--------------- | 1 | 1 | 1 | zxc23 | --------------+-------------+----------+--------------+ | 2 | 1 | 2 | rtc26 | --------------+-------------+----------++-------------+ | 3 | 2 | 1 | z8723 | --------------+-------------+----------+--------------+ | 4 | 2 | 2 | h7c26 | --------------+-------------+----------++-------------+ | 5 | 2 | 2 | rrcf6 | --------------+-------------+----------++-------------+ | 6 | 2 | 3 | r7y28 | --------------+-------------+----------++-------------+ | 7 | 2 | 3 | bnc26 | --------------+-------------+----------++-------------+
$campaign = DB::table('campaign')
->select('campaign.*', DB::raw('count(gift_code.batch) as batch_count')->groupBy('gift_code.campaign_id')->groupBy('gift_code.batch'))
->leftjoin('gift_code', 'campaign.campaign_id', '=', 'gift_code.campaign_id')
->get();
我的预期结果是:
--------------+-------------------------+ |campaign_id | name |batch_count| --------------+-------------+-----------+ | 1 | abc | 2 | --------------+-------------+-----------+ | 2 | xyz | 3 | --------------+-------------+-----------+
答案 0 :(得分:1)
尝试下面的查询
$data = \DB::table('campaign as c')
->leftJoin('gift_code as gc','c.campaign_id','=','gc.campaign_id')
->select('c.*',\DB::raw('COUNT(distinct(gc.batch)) as batch_count'))
->groupBy('c.campaign_id')
->get();