我想列出列表中用户的所有消息。我能够列出所有邮件但我想要一份不同的发件人列表。它类似于facebook消息视图
我有消息表的这种布局
CREATE TABLE [dbo].[messages](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[reciever] [varchar](50) NULL,
[sender] [varchar](50) NULL,
[posted] [datetime] NULL,
[message] [varchar](1000) NULL,
[status] [varchar](1) NULL
)
接收者和发件人是此表的外键
CREATE TABLE [dbo].[accounts](
[uname] [varchar](50) NOT NULL,
[pword] [varchar](32) NULL,
[fname] [varchar](50) NULL,
[mname] [varchar](50) NULL,
[lname] [varchar](50) NULL
)
我尝试过这个查询,但它不起作用
SELECT [status], posted, sender, (
SELECT DISTINCT sender FROM [messages] b
WHERE a.sender = b.sender
) AS sender FROM [messages] a
目标是列出所有邮件,但不同/唯一的发件人。
提前致谢
答案 0 :(得分:1)
我终于明白了!大声笑 我只是在WITH查询块
中添加条件WITH latestMessages
AS
(
SELECT ID, receiver, sender, posted, message, status,
ROW_NUMBER() OVER (Partition BY Sender
ORDER BY posted DESC) RN
FROM messages
WHERE receiver = 'admin'
)
SELECT ID, receiver, sender, posted, message, status
FROM latestMessages
WHERE RN = 1
这是一种非常简单快捷的方法,而不是执行两个单独的查询。
PS:如何将其标记为已解决?
答案 1 :(得分:0)
;WITH latestMessages
AS
(
SELECT ID, receiver, sender, posted, message, status,
ROW_NUMBER() OVER (Partition BY Sender
ORDER BY posted DESC) RN
FROM messages
)
SELECT ID, receiver, sender, posted, message, status
FROM latestMessages
WHERE RN = 1
答案 2 :(得分:0)
我能够解决这个问题。 我所做的是列出收件人的所有邮件
SELECT DISTINCT sender FROM messages WHERE receiver = 'someuser'
然后获取接收器的最近消息
SELECT TOP (1) message, posted FROM messages WHERE receiver = 'someuser' AND sender = 'anotheruser' ORDER BY posted DESC
我是通过使用我使用的编程语言的一些函数来实现的,这是.NET