作者:嘲笑讽刺伤 | 来源:互联网 | 2023-10-16 18:30
我想获得具有相同日期的行数.但一秒钟必须可以忽略不计.例如;2012-01-0313:12:28和2012-01-0313:12:27应该被认为是一样的.(我的表名是myTable
我想获得具有相同日期的行数.但一秒钟必须可以忽略不计.
例如 ; 2012-01-03 13:12:28和2012-01-03 13:12:27应该被认为是一样的.
(我的表名是myTable,日期时间列名是date)
我希望你能帮助我..
解决方法:
它很简单:
SELECT * FROM myTable WHERE date >= '2012-01-03 13:12:27' AND date <= '2012-01-03 13:12:28';
如果你想从变量构建它,你可以这样做:
$date = '2012-01-03 13:12:27';
$timestamp = strtotime($date);
$mysqli = new mysqli();
// Note: allowing 1 second either side, this is up to you
$lower = date('Y-m-d H:i:s', $timestamp - 1);
$upper = date('Y-m-d H:i:s', $timestamp + 1);
$stmt = $mysqli->prepare('SELECT * FROM myTable WHERE date >= ? AND date <= ?');
$stmt->bind_param('ss', $lower, $upper);
$stmt->execute();
编辑:根据您的评论,下面的SQL应该返回您所追求的内容.请注意,如果日期包含“2012-01-03 13:12:28”,则将同时计算:27和:28.
SELECT
upper_date,
COALESCE(lower_count, 0) + upper_count
FROM
(SELECT
date AS upper_date,
COUNT(1) AS upper_count
FROM myTable
GROUP BY date
) AS upper
LEFT JOIN
(SELECT
date - INTERVAL 1 SECOND AS lower_date,
COUNT(1) AS lower_count
FROM myTable
GROUP BY date
) AS lower
ON upper.upper_date = lower.lower_date