问题
I'm trying to write a mysql statement that pulls only unique messages from my chat system. There is a to_id and a from_id. I want to pull one row from every conversation.
The problem is if there is a row with to_id = 1 from_id = 2 and another row with to_id = 2 from_id = 1 I want both of these rows to be treated as the same.
The statement I came up with is "SELECT * FROM chat_messages GROUP BY to_id,from_id ". This works except for the situation I mentioned above.
Another attempt I made was using "SELECT DISTINCT least(to_id,from_id) as value1, greatest(to_id,from_id) as value2 from chat_messages ".
This returns what I need but I do not know how to get the rest of the information from the row like the message, timestamp etc. It only gives me value1 & value2 which are the to_id & from_id.
回答1:
Just use the expressions in the second query for the GROUP BY of the first query:
SELECT * FROM chat_messages GROUP BY LEAST(to_id,from_id), GREATEST(to_id,from_id)
回答2:
If second query returns what you expect, then below query returns rest information:
SELECT *
FROM chat_messages t1 INNER JOIN (
SELECT DISTINCT LEAST(to_id, from_id) AS value1,
GREATEST(to_id, from_id) AS value2
FROM chat_messages
) t2 ON t1.to_id = value1 AND t1.from_id = value2;
来源:https://stackoverflow.com/questions/26707468/mysql-statement-to-select-distinct-rows-from-two-columns