我有两张桌子:
UserTable包含(UserID,UserName)和StoryTable (StoryID,UserID(foreignkey),StoryName,InsertedDate)
如何查询每个用户名以及他发布的最新故事名称? (我很擅长查询这么好的借口,如果它非常基本的话)
我试过了:
选择a.Username,b.StoryName FROM [dbo]。[UserTable]作为INNER JOIN [dbo]。[StoryTable] as b ON a.UserID = b.UserID WHERE InsertedDate = MAX(InsertedDate)组由a.UserName;
组成
但它在sql server 2008中抛出错误。
答案 0 :(得分:3)
将您的查询更改为:
SELECT a.Username, b.StoryName
FROM [dbo].[UserTable] as A
INNER JOIN [dbo].[StoryTable] as b ON a.UserID = b.UserID
WHERE b.InsertedDate =
(SELECT MAX(InsertedDate) FROM [StoryTable] AS z WHERE z.UserID = A.UserID)
根据评论编辑:
SELECT a.Username, b.StoryName
FROM [dbo].[UserTable] as A
INNER JOIN [dbo].[StoryTable] as b ON a.UserID = b.UserID
WHERE b.StoryID =
(SELECT MAX(z.StoryID) FROM [StoryTable] AS z WHERE z.UserID = A.UserID)
答案 1 :(得分:1)
SELECT Top 1 a.Username, b.StoryName
FROM [dbo].[UserTable] as A
INNER JOIN [dbo].[StoryTable] as b ON a.UserID = b.UserID
order by b.InsertedDate desc
答案 2 :(得分:0)
你可以这样做
SELECT u.Username, s.StoryName
FROM [dbo].[UserTable] AS u
CROSS APPLY (SELECT TOP 1 StoryName
FROM [dbo].[StoryTable] AS ss
WHERE ss.UserID = u.UserID
ORDER BY ss.InsertedDate DESC
) AS s
答案 3 :(得分:0)
MAX是一个聚合函数,要使用聚合函数进行过滤,需要使用HAVING关键字而不是WHERE