如何为DISTINCT使用多个列?

时间:2018-04-24 08:07:15

标签: mysql sql

我正在建立一个消息系统。消息是两种不同的类型。

  • 第一封邮件的title列为NULLrelated
  • 第二条消息与第一条消息之一相关,这些消息中没有title,并且它们具有related列的父消息。

这是我的表结构:

// 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  |          | whatever6        | 5         | 1           | 1521097245  | 5       |
| 7  |          | whatever7        | 4         | 1           | 1521097246  | 4       |
| 8  | title4   | whatever8        | 1         | 4           | 1521097246  | NULL    |
+----+----------+------------------+-----------+-------------+-------------+---------+
/*
  related column: it is NULL for the first message and the id of the parent for othesrs.

现在,我需要将用户每天发送给不同用户和不同新消息的消息数量计算在内。

因此4的预期结果为sender_id = 1。这是我当前的查询,它返回3

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 个答案:

答案 0 :(得分:2)

尝试以下查询

SELECT sum(sent_messages_num)
FROM
(
    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))
    GROUP BY CASE WHEN related IS NULL THEN id ELSE related END
) t

dbfiddle demo