SQL Query返回其中一个

时间:2014-09-10 09:39:43

标签: sql sql-server

select DISTINCT first_name, last_name, picture, last_active, id_participante1, id_participante2, id_user, [message], dataHora from chat_b_users inner join utilizadores
on chat_b_users.id_participante2 = utilizadores.id_user
left join chat_talks on chat_b_users.id_chat = chat_talks.id_chat
where id_participante1 = 1
union all
select DISTINCT first_name, last_name, picture, last_active, id_participante1, id_participante2, id_user, [message], dataHora from chat_b_users inner join utilizadores 
on chat_b_users.id_participante1 = utilizadores.id_user
left join chat_talks on chat_b_users.id_chat = chat_talks.id_chat
where id_participante2 = 1 order by last_active DESC

如何选择不同的值?

我需要返回所有这些数据,即使是null,但每个用户,我该如何做到这一点?

结果:

enter image description here

正如你在图片中看到的,我有两个来自同一个用户的聊天,我只想要其中一个。

2 个答案:

答案 0 :(得分:2)

尝试此操作:在代码中添加列列表以标识要显示的行。

 SELECT first_name, last_name, picture, last_active, id_participante1, id_participante2, id_user, [message], dataHora
(
select DISTINCT first_name, last_name, picture, last_active, id_participante1, id_participante2, id_user, [message], dataHora ,
ROW_NUMBER (PARTITION BY <add_yr_colist> ORDER BY Last_Avtive DESC) AS RNUM 
from chat_b_users inner join utilizadores
on chat_b_users.id_participante2 = utilizadores.id_user
left join chat_talks on chat_b_users.id_chat = chat_talks.id_chat
where id_participante1 = 1 OR id_participante2 = 1
)TVC WHERE RNUM = 1

答案 1 :(得分:0)

您需要使用UNIION代替UNION ALL,如下所示:

select DISTINCT first_name, last_name, picture, last_active, id_participante1, id_participante2, id_user, [message], dataHora from chat_b_users inner join utilizadores
on chat_b_users.id_participante2 = utilizadores.id_user
left join chat_talks on chat_b_users.id_chat = chat_talks.id_chat
where id_participante1 = 1
union 
select DISTINCT first_name, last_name, picture, last_active, id_participante1, id_participante2, id_user, [message], dataHora from chat_b_users inner join utilizadores 
on chat_b_users.id_participante1 = utilizadores.id_user
left join chat_talks on chat_b_users.id_chat = chat_talks.id_chat
where id_participante2 = 1 order by last_active DESC

UNION删除重复记录(结果中的所有列都相同),UNION ALL不

Difference betwwen UNION & UNION ALL