[英]How to SUM two fields within an SQL query and make a condition for that SUM
I have a table students
and table room
我有一个桌子
students
和一个桌子room
The room
table contains a capacityField
(int) and margeField
(int) of how many student can support. room
表包含一个capacityField
(int)和margeField
(int)可以支持多少学生。
example : 例如:
capacityField : 100
margeField : 12
I want to retrieve the rooms
which capacityField + margeField
is supperior or equal to the total of students. 我想检索
capacityField + margeField
大于或等于学生总数的rooms
。
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. 您不能将同一查询的
SELECT
别名放在其WHERE
子句中。 You either have to use HAVING
: 您要么必须使用
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. 另外,您应该学习使用准备好的查询和
bindParam
而不是将变量替换为SQL字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.