php - is it possible to use more than 1 query in mysql?
问题描述
hi guys i have a doubt here, i have my website and im trying to echo in php from my database the max temperature, minimum temperature, most recent temperature that entered the DB and i´ve looked around and it seems that i need to use 2 queries by using the UNION from Mysql and i used it but now it only shows the max temperature in DB from the current day here is my code:
$connect = mysqli_connect(".....", ".....", "....", ".....");
$sql ="SELECT MAX(temperature) as max_temperature , MIN(temperature) as min_temperature
FROM sensor
WHERE DATE(data) = CURDATE()
UNION
SELECT temperature, data
FROM sensor
ORDER BY data DESC
LIMIT 1";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result)) {
$max_temperature = number_format($row['max_temperature'], 1, '.', ',');/*armazena dados vindo da B.D */
$temperature = number_format($row['temperature'], 1, '.', ',');
$min_temperature = number_format($row['min_temperature'], 1, '.', ',');
}
echo "<h4>".$max_temperature."</h4>";
echo "<h3>".$temperature."</h3>";
echo "<h4>".$min_temperature."</h4>";
much apreciated all the help guys!
解决方案
UNION
seems unessary here, and adds complexity client-side. You can get the three information that you want on a single row (so without UNION
) with the following query:
SELECT
MAX(temperature) max_temperature,
MIN(temperature) min_temperature,
(SELECT temperature FROM sensor ORDER BY data DESC LIMIT 1) current_temperature
FROM sensor
WHERE data >= current_date AND data < current_date + 1 day
I am unsure whether window functions would perform better (this requires MySQL 8.0 though):
SELECT DISTINCT
MAX(temperature) OVER() max_temperature,
MIN(temperature) OVER() min_temperature,
FIRST_VALUE(temperature) OVER(ORDER BY date DESC) current_temperature
FROM sensor
WHERE data >= current_date AND data < current_date + interval 1 day
推荐阅读
- typescript - 笑话:测试完成后无法登录
- javascript - 在 html 页面中加载 html 元素
- flutter - 使用 Flutter BLoc 登录 Google 失败
- uwp - 如何获取主 AppWindow 的实例?
- iar - STEVAL-IDB008V1 的测试应用程序
- android - 在进行发布构建时出现错误:程序类型已存在:okhttp3.Call$Factory
- sql - 复制 SQL 内连接中的值,
- r-mice - 如何将 mimira 对象(Cox 回归模型,来自多重插补和倾向得分匹配 (MatchThem pkg))转换为森林图
- python - 当为多个输入调用 model.fit 函数时,会引发基数问题
- java - CheckStyle 将 2-space 更改为 4-space 缩进