I am trying to declare variables and run the query like this:
$sql = "SELECT @dateconsult := (YEARWEEK('2018-10-01',3)),
@countunits := ( SELECT COUNT(s.id_production)
FROM sw_sowing
WHERE status != 0
AND YEARWEEK(date,3) <= @dateconsult
GROUP BY id_production_unit_detail
),
@quadrants := ( SELECT DISTINCT value
FROM cf_config
WHERE parameter = 'PLANTHEALTH'
);
SELECT FORMAT(((count_quadrant * 100)/(total_units * Cuadrantes)),3) AS incidence
FROM (
SELECT @countunits AS total_units, @quadrants AS Cuadrantes,
FROM ph_planthealth
INNER JOIN ph_planthealth_detail ON ph_planthealth_detail.id_p = ph_planthealth.id
WHERE YEARWEEK(ph_planthealth.date,3) = @dateconsult
AND ph_planthealth.status = 200
AND ph_planthealth.id_tenant = 1
AND ph_planthealth_detail.id_plague != 0
GROUP BY ph_planthealth_detail.id_plague
) AS s
ORDER BY incidence DESC; ";
$plague = $this->db->fetchAll($sql, Phalcon\Db::FETCH_ASSOC, $options) ";
the problem is that it shows the result of the first SELECT which are the variables that I declared and not the one of the second SELECT that is the main query.
It's the first time I declare variables and I do not know if I'm doing it right.
I appreciate your comments and help regarding this topic.
You don't need to do the variable assignments in a separate SELECT
. You can do them by joining with the main query.
SELECT FORMAT(((count_quadrant * 100)/(total_units * Cuadrantes)),3) AS incidence
FROM (
SELECT @countunits AS total_units, @quadrants AS Cuadrantes,
FROM ph_planthealth
INNER JOIN ph_planthealth_detail ON ph_planthealth_detail.id_p = ph_planthealth.id
WHERE YEARWEEK(ph_planthealth.date,3) = @dateconsult
AND ph_planthealth.status = 200
AND ph_planthealth.id_tenant = 1
AND ph_planthealth_detail.id_plague != 0
GROUP BY ph_planthealth_detail.id_plague
) AS s
CROSS JOIN (
SELECT @dateconsult := (YEARWEEK('2018-10-01',3)),
@countunits := ( SELECT COUNT(s.id_production)
FROM sw_sowing
WHERE status != 0
AND YEARWEEK(date,3) <= @dateconsult
GROUP BY id_production_unit_detail
),
@quadrants := ( SELECT DISTINCT value
FROM cf_config
WHERE parameter = 'PLANTHEALTH'
)
) AS vars
ORDER BY incidence DESC