如何在SQL查询中SUM两个字段并为该SUM创建条件

时间:2015-05-09 15:20:10

标签: php sql

我有一张桌子students 和表格room

room表包含capacityField(int)和margeField(int),表示有多少学生可以支持。

示例:

capacityField : 100
margeField : 12

我想要检索rooms capacityField + margeField,其中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(); } 超出或等于学生总数。

我提出了这个问题:

{{1}}

但我不工作

1 个答案:

答案 0 :(得分:1)

您无法在其SELECT子句中放置同一查询的WHERE别名。您必须使用HAVING

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

或者您必须重复计算:

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

顺便说一句,您可以将两个查询合并为一个:

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

此外,您应该学会使用准备好的查询和bindParam,而不是将变量替换为SQL字符串。