日期:2014-05-16 浏览次数:20613 次
IF OBJECT_ID('tempdb..#Users') IS NOT NULL
BEGIN
DROP TABLE #Users;
END
GO
CREATE TABLE #Users
(
Id INT IDENTITY(1, 1)
NOT NULL
PRIMARY KEY ,
Name VARCHAR(50) NOT NULL
);
GO
INSERT INTO #Users
VALUES ( 'zhangsan' ),
( 'lisi' ),
( 'wangwu' ),
( 'zhaoliu' );
GO
IF OBJECT_ID('tempdb..#Messages') IS NOT NULL
BEGIN
DROP TABLE #Messages;
END
GO
CREATE TABLE #Messages
(
id INT IDENTITY ,
sendUserID INT ,
recvUserID INT ,
content VARCHAR(100)
);
GO
INSERT INTO #Messages
VALUES ( 1, 2, '我是3号,2号你好' ),
( 1, 3, '3号你好' ),
( 1, 4, '4号你好' ),
( 4, 1, '我是4号,1号你好烦' ),
( 2, 1, '我是2号,1号你好烦' ),
( 3, 2, '我是3号,2号你好' );
GO
SELECT *
FROM #Users;
SELECT *
FROM #Messages;
GO
/*
查询标识为1的用户和其它用户的最后聊天记录;
*/
DECLARE @id INT = 1;
SELECT t.*
FROM #Users AS u
CROSS APPLY ( SELECT TOP 1
*
FROM &nb