查询条件,如果不加0

时间:2019-01-06 06:56:25

标签: laravel laravel-5 laravel-5.7

我有一个Laravel 5.7查询

$captains = DB::table('pickup_results')
    ->select(DB::raw("playerID"),
        DB::raw("COUNT(CASE WHEN gameResult = 'Win'  THEN 1 END) AS wins"),
        DB::raw("COUNT(CASE WHEN gameResult = 'Loss' THEN 1 END) AS loss"))
    ->where('pickOrder', '=', 0)
    ->where('playerID', '=', $playerID)
    ->groupBy('playerID')
    ->orderBy('wins','DESC')
    ->get();

如果playerID没有“ Win”或“ Loss”,则不会将winsloss的键添加到查询结果中,因此,当用户使用数据库中没有胜利或没有损失。

当数据库中不存在值时,我希望能够将winsloss缺省为0

有人可以帮助我了解我将如何实现吗?

3 个答案:

答案 0 :(得分:1)

假设如果玩家没有赢或输,那么表格中就不会有任何一行,那么您的查询将永远不会返回任何结果。

一种选择(假设您有一个const Person({ String name}) : _name = name; 表)是查询players表,然后左键联接players

pickup_results

或者,由于您在查询中使用$captains = DB::table('players') ->leftJoin('pickup_results', 'players.id', 'pickup_results.playerID') ->select('users.id as user_id', DB::raw("COUNT(CASE WHEN results.gameResult = 'Win' THEN 1 END) AS wins"), DB::raw("COUNT(CASE WHEN results.gameResult = 'Lose' THEN 1 END) AS loss")) ->where('players.id', $playerID) ->where('pickup_results.pickOrder', 0) ->groupBy('players.id') ->orderBy('wins', 'DESC') ->get(); ,因此无论结果如何,都将返回一个集合,因此您可以使用whenEmpty()方法进行链接:

get()

答案 1 :(得分:0)

它将为您提供winsloss的结果。只需在您的else中添加一个case条件,并为draw加上一个额外的计数条件。添加1个以上的orderBy可以更好地表示结果。

$captains = DB::table('pickup_results')
    ->select(DB::raw("playerID"),
        DB::raw("SUM(CASE WHEN gameResult = 'Win'  THEN 1 ELSE 0 END) AS wins"),
        DB::raw("SUM(CASE WHEN gameResult = 'Loss' THEN 1 ELSE 0 END) AS loss")),
       DB::raw("SUM(CASE WHEN gameResult != 'Win' and gameResult != 'Loss' THEN 1 ELSE 0 END) AS draws"))
    ->where('pickOrder', '=', 0)
    ->where('playerID', '=', $playerID)
    ->groupBy('playerID')
    ->orderBy('wins','DESC')
    ->orderBy('draws','DESC')
    ->orderBy('loss','ASC')
    ->get();

答案 2 :(得分:0)

您可以使用SUM()代替COUNT()并将ELSE 0添加到查询中。第一次出现的示例:

DB::raw("SUM(CASE WHEN gameResult = 'Win' THEN 1 ELSE 0 END) AS wins")

或者您可以使用COALESCE(query, 0)

DB::raw("COALESCE(COUNT(CASE WHEN gameResult = 'Win' THEN 1 END), 0) AS wins")

之所以可行,是因为如果所有计数的元素都是COUNT()NULL返回NULL