Laravel中的最佳实践查询计数值?

时间:2019-03-26 14:41:21

标签: php mysql laravel

我有一些桌子 表格解析:

room_id | diag_in | indicator_in | etc..

22      | 0       |    1
23      | 1       |    0
23      | 1       |    1
22      | 0       |    1

我想输出:

room_id | total  

22      | 2       
23      | 3      
SELECT room_id,SUM(total) AS total FROM(

SELECT room_id, COUNT(indicator_in) total
FROM Analytic 
WHERE indicator_in='1'
GROUP BY room_id
UNION
SELECT room_id, COUNT(`diag_in`) total
FROM Analytic 
WHERE diag_in='1'
GROUP BY room_id
) abc
GROUP BY room_id

它的工作原理...但是如果我的表中有23列并且我将在Laravel中实现,那么如何简化代码呢?

1 个答案:

答案 0 :(得分:1)

您可以简单地使用group by和sum来对两列进行计数。

在SQL中:

SELECT room_id, (SUM(indicator_in) + SUM(diag_in)) as total
FROM Analytic
GROUP BY room_id

使用Laravel查询构建器:

DB::table('Analytic')
    ->groupBy('room_id')
    ->select(
        'room_id',
        DB::raw('(SUM(indicator_in) + SUM(diag_in)) as total')
    )
    ->get();