laravel中的COALESCE

rad*_*iis 7 php mysql laravel

是否可以在laravel查询中使用COALESCE.

 $multipleitems = DB::table('votes')
                       ->select('masterItemId',DB::raw('sum(votes) as voteSum'))
                       ->whereBetween('voteDate',array($startDate,$endDate))
                       ->where($condition)
                       ->groupBy('masterItemId')
                       ->get();
Run Code Online (Sandbox Code Playgroud)

这是我的代码,我希望得到每个项目及其总票数.如果没有投票,我想得到'0'.

但在上面的代码中,它返回至少有1票的项目.是否有任何方法可以在laravel中完成此操作?

Sha*_*dow 8

嗯,OP不太有帮助,但我会试一试!我假设,该votes表包含用户对项目的实际投票.这意味着,如果某个项目未收到任何投票,则表格masterItemId中不存在该项目id()votes.

这意味着投票表必须保留在该masterItemId字段的主要项目表上.我将调用主项表:items,并假设它有一个itemId与表中的masterItemId字段匹配的字段votes.在SQL术语中:

select items.itemId, ifnull(sum(votes.votes),0) as votesSum
from items left join votes on items.itemId=votes.masterItemId
where votes.voteDate between ... and ... and <other conditions>
group by items.itemId
Run Code Online (Sandbox Code Playgroud)

我不熟悉Laravel,但是你需要这样的东西,但不要把它当作复制粘贴代码:

$multipleitems = DB::table('items')
                 ->leftJoin('votes','items.itemId','=','votes.masterItemId')
                 ->select('items.itemId',DB::raw('ifnull(sum(votes.votes),0) as voteSum'))
                       ->whereBetween('votes.voteDate',array($startDate,$endDate))
                       ->where($condition)
                       ->groupBy('items.temId')
                       ->get();
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用coalesce()代替ifnull()。 (2认同)