[英]Combine two queries in PostgreSQL
我需要在兩個查詢的單個數組中幫助聯合:
在一個查詢相關的缺席成績的學生在一個季度:
$sSqlAsistencia =
" SELECT
ca.idcadete,
coalesce(sum(i.cantidad),0) as cantidad
FROM
cadetes ca,
cursos c,
cursos_cadetes cc
left join inasistencias i on i.fk_idcurso = cc.fk_idcurso and i.fk_idcadete = cc.fk_idcadete
WHERE
c.habilitado = true
and ca.habilitado = true
and c.fk_idanolectivo = ".$aAnoLectivoBuscar."
and c.fk_idano = ".$aAnoBuscar."
and c.fk_iddivision = ".$aDivisionBuscar."
and cc.fk_idcurso = c.idcurso
and cc.fk_idcadete = ca.idcadete
and (EXTRACT(MONTH FROM i.fecha) in ".$trimestre ." or i.cantidad is null)
GROUP BY
ca.idcadete
";
$sSqlInasistencia = $oDB->Query($sSqlAsistencia);
idcadete | cantidad
203 | 4
305 | 0
120 | 10
然后我得到的一段代碼是學生/學員獎,用於滿足其他問題:
$sSql = " SELECT idcadete, nombre, apellido, matricula
FROM cadetes
WHERE idcadete in
(" . $sSqlPromedioEnCadaMateria . " INTERSECT " . $sSqlPromedioConducta;
if (strlen($aPromedioGeneralEdFisicaMayorABuscar)) {
$sSql .= " INTERSECT " . $sSqlPromedioEnEdFisica;
}
$sSql .= ")";
$rsCadetesConPremio=$oDB->query($sSql);
idcadete | nombre | apellido | matricula
203 | adrian | perez | 212121
嘗試將這兩次咨詢與INNER JOIN聯系起來但是我錯了,因為它應該設法將這兩個查詢組合在一起:
$premio = " SELECT a.idcadete, a.nombre, a.apellido, a.matricula, b.cantidad
FROM ".$rsCadetesConPremio."a inner join ".$sSqlInasistencia."b on a.idcadete = b.idcadete
ORDER BY a.idcadete";
- - 錯誤 - - - -
我需要以下結果:$ premio
idcadete | nombre | apellido | matricula| cantidad
203 | adrian | perez | 212121 | 4
是的,您應該能夠通過將兩者的結果包裝為派生表來加入任意兩個任意查詢。 但是,您需要將兩個派生表括在括號中: FROM ( ...) a INNER JOIN ( ...) b
即:
"SELECT a.idcadete, a.nombre, a.apellido, a.matricula, b.cantidad
FROM (".$rsCadetesConPremio.") a inner join (".$sSqlInasistencia.") b on a.idcadete = b.idcadete
ORDER BY a.idcadete"
這是一個簡化的小提琴 。
$sSqlAsistencia = " SELECT ca.idcadete, ca.nombre, ca.apellido, ca.matricula coalesce(sum(i.cantidad),0) as cantidad FROM cadetes ca, cursos c, cursos_cadetes cc left join inasistencias i on i.fk_idcurso = cc.fk_idcurso and i.fk_idcadete = cc.fk_idcadete WHERE c.habilitado = true and ca.habilitado = true and c.fk_idanolectivo = ".$aAnoLectivoBuscar." and c.fk_idano = ".$aAnoBuscar." and c.fk_iddivision = ".$aDivisionBuscar." and cc.fk_idcurso = c.idcurso and cc.fk_idcadete = ca.idcadete and (EXTRACT(MONTH FROM i.fecha) in ".$trimestre ." or i.cantidad is null) and ca.idcadete in (" . $sSqlPromedioEnCadaMateria . " INTERSECT " . $sSqlPromedioConducta; if (strlen($aPromedioGeneralEdFisicaMayorABuscar)) { $sSqlAsistencia .= " INTERSECT " . $sSqlPromedioEnEdFisica; } $sSqlAsistencia .= ") GROUP BY ca.idcadete ";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.