我有一个包含一些数据的数据库。
例如:
Time Type
1:00 123
2:00 123
3:00 123
4:00 123
5:00 113
6:00 113
7:00 113
8:00 113
9:00 334
10:00 334
11:00 334
12:00 123
我希望DB的输出像这样:
At 5:00 type changed from 123 to 113
At 9:00 type changed from 113 to 334
At 12:00 type changed from 334 to 123
我已经通过GROUP BY尝试了,但是只输出了不同的值,所以没关系,但是当有相同的日期类型时,它只输出第一个更改,因为它只被分组为一个,当然...
有人可以帮助我吗?
答案 0 :(得分:0)
如果能解决您的问题,请不要忘记将此答案标记为“已解决”。
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Time, Type FROM MyTable";
$result = $conn->query($sql);
// Declare 4 variables to store time and type so you can compare to previous.
$time1 = "";
$type1 = "";
$time2 = "";
$type2 = "";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$time2 = $row["Time"];
$type2 = $row["Type"];
if ($type2 == $type1) {
$time1 = $time2;
$type1 = $type2;
}
else {
echo "At $tim2 type changed from $type1 to $type2";
$time1 = $time2;
$type1 = $type2;
}
}
}
else {
echo "0 results";
}
$conn->close();
?>
您可以缩短循环代码并写下:
while($row = $result->fetch_assoc()) {
$time2 = $row["Time"];
$type2 = $row["Type"];
if ($type2 != $type1) {
echo "At $tim2 type changed from $type1 to $type2";
}
$time1 = $time2;
$type1 = $type2;
}
要在循环开始时排除第一个结果,请写下:
while($row = $result->fetch_assoc()) {
$time2 = $row["Time"];
$type2 = $row["Type"];
if ($type2 != $type1 && $type1 != "") {
echo "At $tim2 type changed from $type1 to $type2";
}
$time1 = $time2;
$type1 = $type2;
}