我有一张这样的表:
// messages
+----+----------------+-----------+-------------+-------------+
| id | content | sender_id | receiver_id | date_time |
+----+----------------+-----------+-------------+-------------+
| 1 | whatever1 | 1 | 3 | 1521097240 |
| 2 | whatever2 | 3 | 1 | 1521097241 |
| 3 | whatever3 | 1 | 3 | 1521097242 |
| 4 | whatever4 | 1 | 4 | 1521097243 |
| 5 | whatever5 | 1 | 5 | 1521097244 |
| 6 | whatever6 | 5 | 1 | 1521097245 |
+----+----------------+-----------+-------------+-------------+
现在我需要计算用户sender_id = 1
给不同人的消息数量。因此,假设所有这些行都在过去一天,那么结果应为3
。因为sender_id = 1
已向receiver_ids = 3,4,5
发送了邮件。我怎么能在Mysql中做到这一点?
这是我尝试过的:
SELECT count(1) as sent_messages_num
FROM messages
WHERE sender_id = 1
AND date_time > UNIX_TIMESTAMP(DATE_SUB(now(), INTERVAL 1 DAY))
所以我需要添加一个分组。但不确定我该怎么做?
答案 0 :(得分:1)
尝试使用以下查询:
SELECT count(*) as sent_messages_num, receiver_id
FROM users
WHERE sender_id = 1
AND date_time > UNIX_TIMESTAMP(DATE_SUB(now(), INTERVAL 1 DAY))
GROUP BY receiver_id
这将为您提供每个接收者的消息数量。在我再次阅读答案之后,我认为以下内容可能更适合:
SELECT count(DISTINCT receiver_id) as sent_messages_num
FROM users
WHERE sender_id = 1
AND date_time > UNIX_TIMESTAMP(DATE_SUB(now(), INTERVAL 1 DAY))
答案 1 :(得分:1)
您需要在distinct
COUNT
SELECT count(distinct receiver_id) as sent_messages_num
FROM users
WHERE sender_id = 1
AND date_time > UNIX_TIMESTAMP(DATE_SUB(now(), INTERVAL 1 DAY))