php - 如何在 Laravel 中的 unionAll 之后将 group by 添加到 eloquent 查询?
问题描述
我想将此 Mysql 代码转换为 Laravel Eloquent
select service_id, sum(cnt) from
(
select * from
(
select service_id, count(*) cnt from prdouct_notifs
join products on products.id = prdouct_notifs.product_id
where prdouct_notifs.user_id = 268
and prdouct_notifs.deleted_at is null
and prdouct_notifs.block = 4
group by service_id
) first_table
union All
(
select service_id, count(*) cnt from products
where products.pro_user_id = 268
and products.status = 47575
group by service_id
)
) total_union group by service_id
我将此代码更改为 Laravel Eloquent。
$get_product = Product::where('pro_user_id', 268)
->where('status', 47575)
->groupby('service_id')
->selectRaw('service_id ,count(*) cnt');
$get_final_product = prdouct_notifs::join('products', function ($join){
$join->on('products.id', '=', 'prdouct_notifs.product_id')
->where('prdouct_notifs.user_id', 268)
->where('prdouct_notifs.block', 4);
})
->selectRaw('service_id ,count(*) cnt')
->groupby('service_id')
->unionAll($get_product)
->get();
问题是如何在 unionAll 之后运行 groupby
这就是我想改成雄辩的。
total_union group by service_id
解决方案
我的想法是在分组之前将 UNION 放入子查询中。我希望这能回答你的问题。
$product = DB::table('products as p')
->where('p.status', 47575)
->select('p.service_id as service_id');
$productNotify= DB::table('prdouct_notifs as pn')
->select('pn.service_id as service_id')
->union($product);
$groupby = DB::query()->fromSub($productNotify, 'p_pn')
->select('service_id', DB::raw('COUNT(*) as cnt'))
->groupBy('service_id');
产生以下 SQL
select "stud_id", COUNT(*) as total_asset from (
select * from (select p.service_id as service_id from products as p)
union
select * from (select pn.service_id as service_id from prdouct_notifs as pn)
) as p_pn
group by service_id
推荐阅读
- python - 使用 head_object 时为键值使用变量 - Amazon S3 Boto3
- vue.js - 在 vue.js 模板中显示主机名
- delphi - 获取 SQL 来比较数据库
- python - 如何使用 IF 语句对 Pandas 的多个条件进行分类
- javascript - 将表单数据收集到 Google 表格时遇到更多麻烦
- youtube-iframe-api - 在接受中文的视频上对 cc_lang_pref 使用“zh”时,隐藏式字幕显示为英文
- c# - 使用 c# 问题将图像上传到 azure blob 存储
- gcc - 组装中位测试后的条件异或
- python - 如何按 2 个变量排序并按 1 个变量选择以创建数据框
- python - 如何在 Python 中使用 remove.bg 删除照片的背景