mysql - Laravel 雄辩的查询具有 JOIN 和子查询
问题描述
我必须在 Laravel eloquent (查询生成器)中使用查询,但我不确定如何转换它:
SELECT c.*, m.*,th.team as team_home, ta.team as team_away from schedule as c
LEFT JOIN matches as m ON m.id_match = c.match_id
LEFT JOIN teams as th ON m.team_h = th.id_team
LEFT JOIN teams as ta ON m.team_a = ta.id_team
WHERE c.serie_id = :sid and c.days =(
SELECT c.days from schedule as c
LEFT JOIN matches as m ON m.id_match = c.match_id
WHERE c.serie_id = :sid and m.match_stato = 2 order by c.days DESC LIMIT 1
) order by c.days, th.team ASC
正如您所注意到的,它有 3 个 JOINS 和一个子查询,而不是两个订单。如何在 Eloquent 中使用它?
解决方案
对于这种性质的子查询,您可以使用whereIn()
.
此外,对于子查询内部的逻辑order by c.days DESC LIMIT 1
,您可以只max(c.days)
在 select 子句中使用,而不是 。
DB::table('schedule as c')
->join('matches as m', 'm.id_match', '=', 'c.match_id')
->join('teams as th', 'm.team_h', '=', 'th.id_team')
->join('teams as ta', 'm.team_a', '=', 'ta.id_team')
->where('c.serie_id', '=', $sid)
->whereIn('c.days', function($query) use($sid){
$query->select('max(c.days)')
->from('schedule as c2')
->join('matches as m2', 'm2.id_match', '=', 'c2.match_id')
->where('c2.serie_id', '=', $sid)
->where('m2.match_stato', '=', 2);
})
->select('c.*', 'm.*', 'th.team as team_home', 'ta.team as team_away')
->orderBy('c.days', 'asc')
->orderBy('th.team', 'asc')
->get();
######
推荐阅读
- apache-kafka - Kafka MirrorMaker 2.0 复制流问题:始终写入同一个集群
- html - 将带有 svg 标签的外部文件链接到 HTML
- amazon-web-services - Amazon Connect:没有 CCP 的代理?
- google-chrome - 从 translate.google.com 提取声音
- entity-framework-core - DbContextPool 和 ChangeTracker 事件
- python - 获取按钮以在 django 中执行功能
- javascript - 读取泛型类型并基于它做一些逻辑
- javascript - 在 Chrome 上使用 Javascript 打开和关闭多个选项卡
- python-3.x - 有没有办法以编程方式从 iCloud 中提取电话、消息、电子邮件和应用程序?
- data-visualization - 根据参数显示/隐藏容器