可以将表达式用作结果集中的附加字段:
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)