简体   繁体   English

Mysql语句从两列中选择不同的行

[英]Mysql statement to select distinct rows from two columns

I'm trying to write a mysql statement that pulls only unique messages from my chat system. 我正在尝试编写一个mysql语句,它只从我的聊天系统中提取唯一的消息。 There is a to_id and a from_id. 有一个to_id和一个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. 问题是如果有一行to_id = 1 from_id = 2而另一行有to_id = 2 from_id = 1我希望这两行都被视为相同。

The statement I came up with is "SELECT * FROM chat_messages GROUP BY to_id,from_id ". 我提出的陈述是“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 ". 我做的另一个尝试是使用“SELECT DISTINCT least(to_id,from_id)作为value1,最大(to_id,from_id)作为来自chat_messages的value2”。

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. 这将返回我需要的内容,但我不知道如何从行中获取其余信息,如消息,时间戳等。它只给我value1和value2,它们是to_id和from_id。

只需在第二个查询中使用第一个查询的GROUP BY中的表达式:

SELECT * FROM chat_messages GROUP BY LEAST(to_id,from_id), GREATEST(to_id,from_id)

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM