php - 在mysql中比较两个时间戳,然后返回一个自定义字段

标签 php mysql timestamp

我正在用 PHP 构建一个小规模的论坛脚本,但我很难展示给定线程的已读/未读状态。

所以,我有一个特别庞大的查询,它返回线程信息,包括它首次发布的日期、最后一次发布的日期(如果有的话)以及当前用户最后一次查看它的日期登录用户(如果存在这样的日期。

查询然后返回三个值:

  • 第一个发布日期
  • 上次发布日期
  • 上次查看日期

我需要检查的是,如果 firstPostDate 或 lastPostDate 比 lastViewDate 更新,则将该线程标记为新线程/具有未读回复。

我在 PHP 中执行此操作时遇到问题,因为我的日期都作为时间戳存储在 MySQL 中。起初我以为我可以使用 UNIX_TIMESTAMP 返回一个 Unix 时间戳然后比较它们,但我不相信我得到了正确的结果(因为时间戳是 Y-M-D H-M-S 格式(或类似的,我不记得了我的头顶)。

我在站点中有其他查询比较两个日期,并且看起来效果很好。有没有一种方法可以比较 mysql 查询中的两个或三个日期,如果它是新的则返回"is",如果不是则返回“否”?这将使我的 PHP 标记更加简单。

还是我做错了?

最佳答案

您可以使用表达式作为结果集中的附加字段:

SELECT   ...
         (firstPostDate > lastViewDate OR lastPostDate > lastViewDate) AS unread
FROM     posts;

当线程是新的/有未读回复时,unread 字段应为 1,否则为 0

测试用例:

CREATE TABLE posts (
    id int, 
    firstPostDate timestamp, 
    lastPostDate timestamp, 
    lastViewDate timestamp
);

INSERT INTO posts VALUES (1, '2010-01-01 12:00', '2010-01-02 12:00', '2010-01-03 12:00');
INSERT INTO posts VALUES (2, '2010-01-03 12:00', '2010-01-05 12:00', '2010-01-04 12:00');
INSERT INTO posts VALUES (3, '2010-01-06 12:00', '2010-01-06 12:00', '0000-00-00 00:00');
INSERT INTO posts VALUES (4, '2010-01-07 12:00', '2010-01-07 12:00', '2010-01-08 12:00');

结果:

SELECT   id,
         (firstPostDate > lastViewDate OR lastPostDate > lastViewDate) AS unread
FROM     posts;

+------+--------+
| id   | unread |
+------+--------+
|    1 |      0 |
|    2 |      1 |
|    3 |      1 |
|    4 |      0 |
+------+--------+
4 rows in set (0.01 sec)

关于php - 在mysql中比较两个时间戳,然后返回一个自定义字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3509206/

相关文章:

php - 我无法将数组存储到 MySQL 数据库中,我使用的是 simple_html_dom.php

php - 需要帮忙!我无法使用 codeigniter 在 oracle 11g 中连接我的程序

sql - Oracle SQL - 确定时间戳是否在某个范围内(不包括日期)

php - Codeigniter 数据库更新问题

php - HTML5 服务器发送的事件 : empty response

mysql - MySQL 中替换字符串的问题

mysql - 数据库中的“ts”数字字段? (例如 1428881039)

php - 使用 php 将当前时间戳插入 mysql?

php - Jquery ajax 从 php mysql 检索文本(数字)

php - 数据未在 php 中使用 $_SESSION 变量插入