如何在count查询中使用'as'?

rkttyhzu  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(371)

如何在计数查询中使用as?
事实上我想要这样的结果 { "count":"number" } 对于json结果。我不知道这东西叫什么?

public function firstHourTrades(){

    $user_id = Auth::user()->id;
    $data = DB::table('finaltrade')
        ->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')

        ->where('finaltrade.user_id', $user_id)
        ->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time'))
        ->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '1:00:00')"))
        ->count();

    return response()->json($data);
}
euoag5mw

euoag5mw1#

您还可以执行原始选择并手动分配别名:

$data = DB::table('finaltrade')
    ->select(DB::raw('count(*) as count'))
    ->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
    ->where('finaltrade.user_id', $user_id)
    ->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time'))
    ->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '1:00:00')"))
    ->get();

相关问题