2014-09-10 46 views
0
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 

如何選擇不同的值?SQL Query返回其中之一

我需要返回所有這些數據,即使是空值,但對每個用戶,我怎麼能做到這一點?

結果:

enter image description here

,你可以在圖片中看到,我已經從同一用戶進行的兩次聊天記錄,我只希望每個之一。

+0

您是否試過'SELECT DISTINCT'? – 2014-09-10 09:43:33

+0

是的,我試過了,相同的結果 – Severiano 2014-09-10 09:45:12

+0

我明白了,'DISTINCT'不起作用,因爲組合不同。你的時間戳使他們不會失去意義。用'last_active'試試'MAX',看看它是否有幫助。看看[這個答案](http://stackoverflow.com/questions/5391564/how-to-use-distinct-and-order-by-in-same-select-statement) – 2014-09-10 09:47:51

回答

2

試試這個:在地方的代碼添加你的列清單(S),以確定要顯示哪一行。

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 
+0

這是什麼? – Severiano 2014-09-10 10:08:17

+1

添加一列將標識一個特定的window.say,在你的例子中,你需要顯示user_Id = 40的消息OK,然後用user_id替換,它將根據user_id值對不同窗口中的行進行分區。希望這解釋。 – Rishabh 2014-09-10 10:11:07

+0

誤差在 「PARTITION BY」 – Severiano 2014-09-10 11:22:24

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

+0

這個不工作! – Severiano 2014-09-10 10:04:01

+0

結果是什麼 – Amit 2014-09-10 10:05:16

+0

與另一個相同 – Severiano 2014-09-10 10:05:50