SQL - 提取跨多年范围内的日期

问题描述 投票:0回答:1

在 mySQL 数据库(版本 5.7.44)中,我有许多记录(>30,000),我想从中搜索提供的日期范围内的记录。 目标列是“Visits”表中名为“data”、格式为“Y-mm-dd”的日期字段。 我的应用程序以相同的格式向 PHP 函数发送 2 个字符串(即 2023-05-01 和 2024-05-01)。

这是我的 PHP 函数的剥离代码:

$sDate = $_GET['start'];    //2023-05-01
$eDate = $_GET['end'];      //2024-05-01

$start = date('Y-m-d', strtotime($sDate)); //check OK with echo
$end = date('Y-m-d', strtotime($eDate));  //check OK with echo

$query = "SELECT data FROM Visits WHERE 
data BETWEEN '".$start."' AND '".$end."' GROUP BY MONTH(data) ORDER BY data ASC";

查询运行得几乎很好,但我只得到第一年(2023 年)的行,而没有得到 2024 年几个月的行。 我怀疑 BETWEEN 子句是问题的根源。 我做错了什么?

php mysql
1个回答
0
投票

如果我是你,我会使用准备好的语句,这是你可以使用的示例代码。

// Assuming you have already established a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get date parameters from the GET request
$sDate = $_GET['start']; // e.g., 2023-05-01
$eDate = $_GET['end'];   // e.g., 2024-05-01

// Prepare and bind the SQL statement
$stmt = $conn->prepare("SELECT data FROM Visits WHERE data BETWEEN ? AND ? ORDER BY data ASC");
$stmt->bind_param("ss", $sDate, $eDate); // 'ss' indicates that both parameters are strings

// Execute the statement
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    echo $row['data'] . "<br>";
}

$stmt->close();
$conn->close();

原因:

您在 SQL 查询中遇到的问题可能与 查询中的 GROUP BY 子句。当您按月份(数据)分组时, 您按月汇总结果,这意味着只有一个 每月记录将被返回。如果一个记录有多条 一个月只显示一条,如果一个月没有记录 2024 年,它将不会返回当年的任何结果。

因此,如果您在这里运行小提琴示例:https://www.db-fiddle.com/f/daMHVzaXwDbAdtxHKDuNTx/1由@Ergest Basha分享,您就会明白为什么他在评论中指出了错误。

© www.soinside.com 2019 - 2024. All rights reserved.