2014-10-04 68 views
1

這是我的表:SQL得到最近修改後爲每個用戶

CREATE TABLE [dbo].[posts] 
(
    [id] [int] IDENTITY(1,1) NOT NULL, 
    [user_id] [int] NOT NULL, 
    [date_posted] [datetime] NOT NULL, 
    [date_modified] [datetime] NOT NULL, 
    [content] [text] NOT NULL, 

    CONSTRAINT [PK_posts] PRIMARY KEY CLUSTERED ([id] ASC) 
) 

我的公司需要一個單一的查詢,將獲得最近修改後對每個用戶的帖子的ID。誰能幫幫我嗎?謝謝,

+2

你嘗試過這麼遠嗎?你確定你使用的是MySQL嗎?這看起來更像我的SQL Server語法。 – SchmitzIT 2014-10-04 11:28:11

+0

oops,所以這是SQL,爲什麼我看着mySQL,我不知道這個=。=! – 2014-10-04 11:29:29

回答

3

rank()功能應該做的伎倆:

SELECT user_id, id AS most_recent_post_id 
FROM (SELECT user_id, 
       id, 
       RANK() OVER (PARTITION BY user_id ORDER BY date_posted DESC) AS rk 
     FROM [posts]) p 
WHERE rk = 1