我有DB
,其中有5列如下:
正在寻找SQL服务查询,我希望根据以下约束从给定用户ID的两列(user_id_send
,user_id_rec
)中筛选结果:
此查询的主要目的是获取user_id的记录,以找出他向谁发送消息以及向谁发送消息。
我还附上sheet供您参考。
这是我的尝试
WITH t
AS (SELECT *
FROM messages
WHERE user_id_sender = 1)
SELECT DISTINCT user_id_reciever,
*
FROM t;
WITH h
AS (SELECT *
FROM messages
WHERE user_id_reciever = 1)
SELECT DISTINCT user_id_sender,
*
FROM h;
答案 0 :(得分:0)
select * from
(
select ROW_NUMBER() over (order by message_date DESC) as rowno,
* from messages
where user_id_receiver = 1
--order by message_date DESC
) T where T.rowno = 1
UNION ALL
select * from
(
select ROW_NUMBER() over (order by message_date DESC) as rowno,
* from messages
where user_id_sender = 1
-- order by message_date DESC
) T where T.rowno = 1
说明:对于user_id_sender的每一组,它在内部通过message_date desc命令,然后添加行号,我们只想要第一个(按时间顺序排在最后)。然后对user_id_receiver执行相同操作,并将结果合并在一起以获得包含所有所需行的1个结果集。然后,您可以根据需要添加自己的order by子句和其他条件。
当然,这仅适用于任何1个user_id(使用@user_id替换=1
)。
要立即从所有user_id获取结果,这是一个完全不同的查询,所以我希望这有帮助吗?
答案 1 :(得分:0)
;WITH tmpMsg AS (
SELECT M2.message_id
,M2.user_id_receiver
,M2.user_id_sender
,M2.message_date
,M2.message_details
,ROW_NUMBER() OVER (PARTITION BY user_id_receiver+user_id_sender ORDER BY message_date DESC) AS 'RowNum'
FROM messages M2
WHERE M2.user_id_receiver = 1
OR M2.user_id_sender = 1
)
SELECT T.message_id
,T.user_id_receiver
,T.user_id_sender
,T.message_date
,T.message_details
FROM tmpMsg T
WHERE RowNum <= 1
当您查询特定的user_id时,上面应该会获取您要查找的结果(用参数替换1,例如@p_user_id)。 PARTITION子句中的user_id_receiver + user_id_sender确保未选择具有用户ID组合(如1 - 2,2 - 1)的记录两次。
希望这有帮助。