我从转储中获得了一系列短信,并计划安排它,因此每行只显示每个线程中的最新消息。我在编写此查询时遇到问题但主要是因为发件人始终是相同的数字(gateway number
),因此最好将其分组给收件人(groupby number
)。
我可以想象这就像电子邮件一样,显示的最新消息可以来自发件人或收件人(以最新者为准),但仍由收件人分组。老实说,我不知道如何解决这个问题。
消息表。类型out
表示gateway
已发送,in
表示groupby
已发送。
| id | groupby | gateway | message | type | created |
-------------------------------------------------------------------------------
| 1 | +111 | +789 | Hello | out | 2015-01-01 00:00:00 |
| 2 | +222 | +789 | World | out | 2015-01-02 00:00:00 |
| 3 | +111 | +789 | What's | in | 2015-01-03 00:00:00 |
| 4 | +222 | +789 | New | in | 2015-01-04 00:00:00 |
| 5 | +111 | +789 | With You? | out | 2015-01-05 00:00:00 |
-------------------------------------------------------------------------------
所以结果应该是:
以html结果。
| id | groupby | message | sent from |
------------------------------------------------
| 5 | +111 | With You? | +789 |
| 4 | +222 | New | +222 |
------------------------------------------------
答案 0 :(得分:0)
你可以通过多种方式做到这一点,其中一个是
select
m.* from messages m
join(
select
groupby,
max(created) as created
from messages group by groupby
)m1
on m1.groupby = m.groupby and m1.created = m.created
答案 1 :(得分:0)
SELECT id, `groupby`, message,
(CASE WHEN typo='out' THEN `groupby` ELSE gateway END) AS sentfrom
FROM __table__name
GROUP BY sentfrom ORDER BY created DESC;