我正在尝试计算消息是否被看到/看不见,是否已读/未读。
在data_chats_parties
表格中,有两个字段last_seen
和last_read
在data_chats_messages
表中,有一个字段created
表示消息的创建时间。
我需要从last_seen
中的时间戳中减去last_read
和created
的时间戳。
在对同一个表的列执行数学运算时,查询工作正常,但是当我使用不同的表时,它会返回一个空结果。
这是我现有的查询:
SELECT
data_chats.id AS chat,
data_chats_parties.*,
(SELECT COUNT(data_chats_parties.id) FROM data_chats_parties
WHERE data_chats_parties.chat = data_chats.id) AS total_parties,
data_chats_messages.created AS last_message_created,
data_chats_messages.author AS last_message_author,
data_chats_messages.author_type AS last_message_author_type,
data_chats_messages.message AS last_message,
(data_chats_messages.created - data_chats_parties.last_seen) AS unseen,
(data_chats_messages.created - data_chats_parties.last_read) AS unread
FROM data_chats
INNER JOIN data_chats_parties ON data_chats_parties.chat=data_chats.id
LEFT JOIN data_chats_messages ON data_chats_messages.chat=data_chats.id AND data_chats_messages.active=1
WHERE
data_chats.active=1 AND
data_chats_parties.member=1 AND
data_chats_parties.status >= 1
GROUP BY data_chats_parties.chat
ORDER BY last_message_created DESC
假设此查询按计划运行,如果unread
或unseen
为> 0
,则该查询无法看到或未读。
理想情况下,我可以将unread
和unseen
设置为1
或0
而不是更改值,以便排序更容易,但如果不是可能我的原始方法就足够了。
答案 0 :(得分:1)
尝试使用IF,如下所示:
SELECT
data_chats.id AS chat,
data_chats_parties.*,
(SELECT COUNT(data_chats_parties.id) FROM data_chats_parties
WHERE data_chats_parties.chat = data_chats.id) AS total_parties,
data_chats_messages.created AS last_message_created,
data_chats_messages.author AS last_message_author,
data_chats_messages.author_type AS last_message_author_type,
data_chats_messages.message AS last_message,
IF(data_chats_messages.created > data_chats_parties.last_seen,1,0) AS unseen,
IF(data_chats_messages.created > data_chats_parties.last_read,1,0) AS unread
FROM data_chats
INNER JOIN data_chats_parties ON data_chats_parties.chat=data_chats.id
LEFT JOIN data_chats_messages ON data_chats_messages.chat=data_chats.id AND data_chats_messages.active=1
WHERE
data_chats.active=1 AND
data_chats_parties.member=1 AND
data_chats_parties.status >= 1
GROUP BY data_chats_parties.chat
ORDER BY last_message_created DESC