sql去重并查询其他字段信息
刚开始用法:
select distinct id,* from product_lottery_participants ; 结果只能查询出 id
后面想到用子查询
SELECT * from product_lottery_participants WHERE id in (
SELECT
min( id ) AS mid
FROM
`product_lottery_participants`
WHERE
`product_lottery_id` = 129
GROUP BY
`user_id`
)
lumen 写法:
$query = DB::table('product_lottery_participants')
->selectRaw('min(id) as mid')
->where('product_lottery_id',$productLottery->id)
->groupBy('user_id')
->get()
->toArray();
$list = array_map('get_object_vars', $query);
$ids = array_column($list,'mid');
$productLotteryParticipants = ProductLotteryParticipant::whereProductLotteryId($productLottery->id)->whereIn('id',$ids)->get();
或者直接子查询
$sql = ProductLotteryParticipant::whereProductLotteryId(129)->whereIn('id',function ($query){
$query->selectRaw('min(id) as mid')->from('product_lottery_participants')->where('product_lottery_id',129) ->groupBy('user_id');
})->get()->toArray();