简体   繁体   中英

How to SUM two fields within an SQL query and make a condition for that SUM

I have a table students and table room

The room table contains a capacityField (int) and margeField (int) of how many student can support.

example :

capacityField : 100
margeField : 12

I want to retrieve the rooms which capacityField + margeField is supperior or equal to the total of students.

I made this query:

public function fetchSalle(){
    $cmod = $_GET['cmod'];
    $sth = $this->db->prepare("SELECT * FROM etudiants AS etd INNER JOIN filieres AS flr WHERE etd.id_filiere=flr.id_filiere AND etd.id_filiere=$cmod");
    $sth->execute();
    $total = $sth->rowCount();      

    $stmt = $this->db->prepare("SELECT *, (capaciteField + margeField) AS Sum FROM salles WHERE Sum>=$total");      
    $stmt->execute();

    return $stmt->fetchAll();       
}

but I doesn't work

You can't put a SELECT alias of the same query in its WHERE clause. You either have to use HAVING :

SELECT *, (capaciteField + margeField) AS Sum 
FROM salles 
HAVING Sum>=$total

or you have to repeat the calculation:

SELECT *, (capaciteField + margeField) AS Sum 
FROM salles 
WHERE (capaciteField + margeField) >= $total

BTW, you can combine both queries into one:

SELECT s.*, (capaciteField + margeField) AS Sum
FROM salles AS s
JOIN (SELECT COUNT(*) AS total
      FROM etudiants AS e
      JOIN filieres AS f ON e.id_filiere = f.id_filiere
      WHERE e.id_filiere = $cmod) AS t
WHERE (capaciteField + margeField) > total

Also, you should learn to use prepared queries and bindParam instead of substituting variables into the SQL string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM