1

我想在列表中列出用户的所有消息。我能够列出所有消息,但我想要一个不同发件人的列表。它类似于 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

目标是列出除不同/唯一发件人之外的所有消息。

提前致谢

4

3 回答 3

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:如何将其标记为已解决?

于 2013-01-25T16:48:43.140 回答
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
于 2013-01-15T03:39:02.917 回答
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

于 2013-01-17T11:20:20.773 回答