dpl9717 2015-05-29 10:54
浏览 41
已采纳

将子查询SQL转换为Laravel可能吗?

Is this possible to change this SQL to let it work on Laravel?

SELECT  name, event,m.season_id, tm.played_pugs, active, m.created_at, datediff(now(),m.created_at)
FROM matchs m
LEFT OUTER JOIN seasons ON seasons.id = m.season_id
JOIN ( SELECT season_id, max(matchs.created_at) as MaxDate, count(season_id) as played_pugs
                  FROM matchs
                  GROUP BY season_id) tm on m.season_id = tm.season_id and m.created_at = tm.MaxDate
ORDER BY played_pugs descc>

This is what I have so far:

$seasons = DB::table('matchs')
    ->select('name', 'event', 'season_id', 'played_pugs', 'active', DB::raw('datediff(now(),created_at) as days'))
    ->join('seasons', 'seasons.id', '=', 'matchs.season_id', 'left outer')
    ->join(DB::raw('SELECT season_id, max(matchs.created_at) as MaxDate, count(season_id) as played_pugs FROM matchs GROUP BY season_id)'), '')
    ->orderBy('played_pugs','desc')
    ->get();

Also I can't see the values with 'played_pugs' that have value 0 anymore. How can I fix that.

  • 写回答

1条回答 默认 最新

  • dre93205 2015-05-29 11:45
    关注

    This will generate the exact query you posted. I've built the join subquery using a separate Query Builder object and used the toSql() method to get the generated SQL string to inject using DB::raw(), because it's more readable this way and it's 100% built using the Query Builder syntax.

    $joinSubquery = DB::table('matchs')
        ->select('season_id', DB::raw('max(matchs.created_at) as MaxDate'), DB::raw('count(season_id) as played_pugs'))
        ->groupBy('season_id')
        ->toSql();
    
    $seasons = DB::table('matchs m')
        ->select('name', 'event', 'm.season_id', 'tm.played_pugs', 'active', 'm.created_at', DB::raw('datediff(now(), m.created_at)'))
        ->leftJoin('seasons', 'season.id', '=', 'm.season_id', '')
        ->join(DB::raw('(' . $joinSubquery . ') tm'), function ($join)
        {
            $join->on('m.season_id', '=', 'tm.season_id');
            $join->on('m.created_at', '=', 'tm.MaxDate');
        })
        ->orderBy('played_pugs', 'desc')
        ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作