Answer the question
In order to leave comments, you need to log in
How to remove duplicates in mysql query?
There is a table
id | from_id | to_id
--------------------
1 | 5 | 6
2 | 5 | 7
3 | 5 | 8
4 | 6 | 5
5 | 8 | 6
Answer the question
In order to leave comments, you need to log in
SELECT distinct to_id FROM messages WHERE from_id = 5
SELECT distinct from_id FROM messages WHERE to_id = 5
SELECT to_id as user_id FROM messages WHERE from_id = 5
UNION
SELECT from_id as user_id FROM messages WHERE to_id = 5
SELECT
DISTINCT IF(to_id = 5, from_id, to_id) as user_id
FROM messages
WHERE from_id = 5
OR to_id = 5
SELECT
IF(to_id = 5, from_id, to_id) as user_id,
SUM(unread) as count_unread,
MAX(create_date) as last_create_date
FROM messages
WHERE from_id = 5
OR to_id = 5
GROUP BY user_id
SELECT
IF(m.to_id = 5, m.from_id, m.to_id) as user_id,
SUM(m.unread) as count_unread,
MAX(m.create_date) as last_create_date,
u.name,
u.login
FROM messages as m
LEFT JOIN users as u ON (u.user_id = m.from_id OR u.user_id = m.to_id)
WHERE m.from_id = 5
OR m.to_id = 5
GROUP BY user_id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question