我正在使用 Laravel 5.4 的查询生成器在三个表上执行一系列 leftJoins。这是我的表格:
项目
id type title visibility status created_at
-- ---- ----- ---------- ------ ----------
1 1 This is a Title 1 1 2017-06-20 06:39:20
2 1 Here's Another Item 1 1 2017-06-24 18:12:13
3 1 A Third Item 1 1 2017-06-26 10:10:34
count_loves
id items_id user_id
-- ------- -------
1 1 2
2 1 57
3 1 18
下载次数
id items_id user_id
-- ------- -------
1 1 879
2 1 323
这是我在 Laravel 中运行的代码:
$items_output = DB::table('items')
->leftJoin('count_loves', 'items.id', '=', 'count_loves.items_id')
->leftJoin('count_downloads', 'items.id', '=', 'count_downloads.items_id')
->where('items.visibility', '=', '1')
->where('items.status', '=', '1')
->orderBy('items.created_at', 'desc')
->select('items.*', DB::raw('count(count_loves.id) as loveCount'), DB::raw('count(count_downloads.id) as downloadCount'))
->groupBy('items.id')
->get();
当我返回此查询的结果时,我得到以下计数:
爱次数:6
下载次数:6
如您所见,实际计数值应该是:
爱次数:3
下载次数:2
例如,如果我向 count_loves 表中添加另一个条目,则总数将变为 8。如果我在此之后向 count_downloads 表中添加另一个条目,则总数将变为 8。总数跃升至 12。因此,这两个计数相乘。
如果我死了并转储查询,这就是我得到的:
"query" => "select 'items'.*, count(count_loves.id) as loveCount, count(count_downloads.id) as downloadCount from 'items' left join 'count_loves' on 'items'.'id' = 'count_loves'.'items_id' left join 'count_downloads' on 'items'.'id' = 'count_downloads'.'items_id' where 'items'.'visibility' = ? and 'items'.'status' = ? group by 'items'.'id' order by 'items'.'created_at' desc"
如何使用查询生成器和 count 在多个表上执行多个 leftJoin 以返回正确的总和?
最佳答案
注意:
这旨在作为帮助答案,而不是完全的绝对答案,但我无法在评论中编写代码。我不是在要求投票(对于那些迫不及待地想对我投反对票的人)。我已经创建了您的表并尝试对原始 sql 进行 UNION 查询。我得到了正确的结果。我没有安装 Laravel,但也许你可以在 Laravel 中尝试 UNION 查询。
https://laravel.com/docs/5.4/queries#unions
select count(count_downloads.user_id)
from count_downloads
join items
on items.id = count_downloads.items_id
UNION
select count(count_loves.user_id)
from count_loves
join items
on items.id = count_loves.items_id
关于php - 使用 Laravel 的查询生成器的多个 leftJoins 产生错误的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44761155/