我正在制作一个消息传递系统。消息是两种不同的类型。
title
列为NULL
和related
。title
的第一条消息相关,并且它们具有related
列的父消息ID。 (被称为回复/回复/回答)这是我的表结构:
// messages
+----+----------+------------------+-----------+-------------+-------------+---------+
| id | title | content | sender_id | receiver_id | date_time | related |
+----+----------+------------------+-----------+-------------+-------------+---------+
| 1 | titel1 | whatever1 | 1 | 3 | 1521097240 | NULL |
| 2 | | whatever2 | 3 | 1 | 1521097241 | 1 |
| 3 | | whatever3 | 1 | 3 | 1521097242 | 1 |
| 4 | title2 | whatever4 | 1 | 4 | 1521097243 | NULL |
| 5 | title3 | whatever5 | 1 | 5 | 1521097244 | NULL |
| 6 | | whatever7 | 4 | 1 | 1521097246 | 4 |
| 7 | title4 | whatever8 | 1 | 4 | 1521097246 | NULL |
+----+----------+------------------+-----------+-------------+-------------+---------+
/*
related column: it is NULL for the first message and the id of the parent for othesrs.
现在我需要计算用户A发送的消息数量,并且还没有收到过去一年的响应。
例如,用户user_id = 1
已发送但尚未获得响应的消息数为1
。因为他已向用户user_id = 5
发送了一条消息,但他还没有回复。
我该如何计算这个数字?
SELECT count(1)
FROM messages
WHERE sender_id = 1
AND date_time > UNIX_TIMESTAMP(DATE_SUB(now(), INTERVAL 1 YEAR))
我的查询计算所有已发送的邮件。我怎么能只计算未答复的那些?
答案 0 :(得分:1)
使用NOT EXISTS
SELECT count(1)
FROM messages m1
WHERE sender_id = 1 AND
related IS NULL AND
date_time > UNIX_TIMESTAMP(DATE_SUB(now(), INTERVAL 1 YEAR)) AND
NOT EXISTS (
SELECT 1
FROM messages m2
WHERE m1.id = m2.related
)
答案 1 :(得分:0)
我假设你真的是指" A"发送的第一个消息。如果是这样,您的示例查询需要在related is NULL
上进行过滤。要过滤不答复,您可以使用LEFT JOIN
/ WHERE
或NOT EXISTS
:
SELECT count(*)
FROM messages m LEFT JOIN
messages m2
ON m2.related = m.id
WHERE m.sender_id = 1 AND
m.related IS NULL AND
m.date_time > UNIX_TIMESTAMP(DATE_SUB(now(), INTERVAL 1 YEAR)) AND
m2.id IS NULL; -- response does not exist