PHP – Mysql GROUP BY HAVING Clause
问题陈述:
在本文中,我们将通过 xampp 服务器通过PHP使用 GROUP BY HAVING 操作来执行数据库操作。
在这种情况下,我们将考虑食品数据库。
要求 :
xampp 服务器
介绍 :
PHP是一种服务器端脚本语言,可以通过 xampp 工具与 Mysql web 服务器进行通信。
MySQL是一种查询语言,可以通过xampp与PHP进行通信。
- 按条款分组–
数据库中的 GROUP BY 语句是一条 SQL,用于通过使用 SUM()、MIN()、MAX() 等聚合操作将相同的数据排列成组。
句法 -
SELECT column1,column2,columnn, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2,columnn;
- 按有条款分组–
Have Clause 只是与 GROUP BY 子句一起使用的聚合函数。使用 HAVING 子句代替 WHERE 与聚合函数。而 GROUP BY 子句将具有相同值的行分组为汇总行。 have 子句与 where 子句一起使用,以查找具有特定条件的行。总是在 group By 子句之后使用ifying 子句。
句法 -
SELECT column1,column2,columnn
FROM table_name
GROUP BY column_name
HAVING aggregate_function(column_name) condition;
示例查询:
考虑食物数据库:
选择成本大于 200 的食品
SELECT food_item
from food
GROUP BY(food_item)
HAVING SUM(cost) > 200;
结果:
Item : cakes
Item : chocoss
Item : fry
Item : milk
询问:
重量小于 100 的食品
SELECT food_item
from food
GROUP BY(food_item)
HAVING SUM(weight)>100;
结果:
Item : cakes
方法:
- 在 xampp 中创建数据库
- 创建表并向其中插入记录。
- 编写PHP代码以通过have子句执行组。
脚步 :
- 启动 xampp 服务器
- 创建名为 geek 的数据库
- 创建一个名为 food 的表并在其中插入记录。
请参阅此以将记录插入 xampp :
https://www.geeksforgeeks.org/performing-database-operations-in-xampp/
- 您的表格将如下所示:
- PHP代码(表单PHP)
键入此代码后,通过键入“localhost/form.js”在 Tour Web 浏览器中运行它。 PHP”
PHP
"; echo "GROUP BY HAVING Demo "; echo"";
echo "
";
echo "food items with cost greater than 200";
echo "
";
echo "
";
//sql query
$sql = "SELECT food_item from food GROUP BY(food_item) HAVING SUM(cost)>200";
$result = $conn->query($sql);
//display data on web page
while($row = mysqli_fetch_array($result)){
echo " Item : ". $row['food_item'];
echo "
";
}
echo "
";
echo "food items with weight less than than 100";
echo "
";
echo "
";
//sql query
$sql = "SELECT food_item from food GROUP BY(food_item) HAVING SUM(weight)>100";
$result = $conn->query($sql);
//display data on web page
while($row = mysqli_fetch_array($result)){
echo " Item : ". $row['food_item'];
echo "
";
}
//close the connection
$conn->close();
?>
PHP
"; echo "GROUP BY HAVING Demo "; echo"";
echo "
";
echo "food items with average cost greater than 400";
echo "
";
echo "
";
//sql query
$sql = "SELECT food_item,food_id from food GROUP BY(food_item) HAVING AVG(cost)>400";
$result = $conn->query($sql);
//display data on web page
while($row = mysqli_fetch_array($result)){
echo " Item : ". $row['food_item'], " ---- Item id : ". $row['food_id'];
echo "
";
}
//close the connection
$conn->close();
?>
输出:
示例 2:
- PHP代码(Form1上PHP)
显示平均成本大于 400 的食品
PHP
"; echo "GROUP BY HAVING Demo "; echo"";
echo "
";
echo "food items with average cost greater than 400";
echo "
";
echo "
";
//sql query
$sql = "SELECT food_item,food_id from food GROUP BY(food_item) HAVING AVG(cost)>400";
$result = $conn->query($sql);
//display data on web page
while($row = mysqli_fetch_array($result)){
echo " Item : ". $row['food_item'], " ---- Item id : ". $row['food_id'];
echo "
";
}
//close the connection
$conn->close();
?>
输出: