gpt4 book ai didi

Php-MySql查询,根据DateTime选择数据

转载 作者:可可西里 更新时间:2023-11-01 07:35:50 24 4
gpt4 key购买 nike

我想获取具有相同日期的行数。但是一秒钟肯定可以忽略不计。

例如; 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

关于Php-MySql查询,根据DateTime选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8717492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com