php - 如何在 yii2 'where' 中编写子查询?

标签 php mysql activerecord yii2

我有这个问题:

select * from dias_clases as dc
inner join clases as cl on cl.clase_id = dc.clase
inner join asistencias as asis on asis.dia_clase = dc.dc_id
where( 
clase in(select ce.clase from clases_estudiantes as ce where ce.estudiante = 321)
or dc_id in (select cr.dia_clase from clase_recuperada as cr where cr.estudiante = 321)
)
and fecha < '2017-04-26'
and cl.disciplina = 9
and dc.estado = 1
group by dc.dc_id
order by dc.fecha desc

它在 mysql 控制台中工作正常。我需要在 Yii2 中使用事件记录进行相同的查询,我得到了这个:

$dias_clases = DiasClases::find()
                ->innerJoin("clases as cl", "cl.clase_id = clase")
                ->leftJoin("asistencias as asis", "asis.dia_clase = dc_id")
                ->where("
                    clase in(
                        select ce.clase from clases_estudiantes as ce where ce.estudiante = :estudiante
                    )
                    or dc_id in (
                        select cr.dia_clase from clase_recuperada as cr where cr.estudiante = :estudiante
                    )", [":estudiante" => $estudiante->estudiante_id]
                )
                ->andWhere("fecha < :fecha", [":fecha" => $fecha])
                ->andWhere(["cl.disciplina" => $disciplina])
                ->andWhere(["estado" => DiasClases::TERMINADA])
                ->orderBy(["fecha" => SORT_DESC])
                ->all();

但是“哪里”不能正常工作。我得到的结果是错误的,我认为这是因为这部分:

where( 
    clase in(select ce.clase from clases_estudiantes as ce where ce.estudiante = 321)
    or dc_id in (select cr.dia_clase from clase_recuperada as cr where cr.estudiante = 321)
    )

执行方式与在控制台中的执行方式相同。需要括号

最佳答案

假设您有一个 classes_estudiantes 表的 ClasesEstudiantes 模型,您可以构建一个子查询,例如:

$subquery1 = ClasesEstudiantes::find()
      ->select('clase')->andWhere([ 'estudiante'>=  $estudiante])

DiasClases::find()
     ->innerJoin("clases as cl", "cl.clase_id = clase")
     ->leftJoin("asistencias as asis", "asis.dia_clase = dc_id")
     ->where('in', 'clase', $subquery1)
     .......

you can do the same for the other subquery  using `orWhere(   )`

关于php - 如何在 yii2 'where' 中编写子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43669143/

相关文章:

php - 使用多种不同查询的高级搜索查询

php - 如何将多维数组键作为树返回?

javascript - 加载 gif 直到页面完全加载

ruby-on-rails - 如何让我的独立 ActiveRecord::Base 工具连接到我的生产数据库?

codeigniter - 如何使用 ActiveRecord 和 mySQL 函数作为 WHERE 条件删除记录

php - 为什么此邮件消息不能正确解码?

mySQL:为什么 if(condition,then ,'' ) != '' 与 if(condition,then,0) != 0 不同

php - 我需要从 MySQL 数据库获取一些信息并打印出来

mysql - 类似 SERIAL 的 INT 列

mysql - 替换 nodejs 中 codeigniter 的事件记录