MySQL - 通过比较两列来选择行

时间:2013-11-26 05:41:59

标签: mysql select

enter image description here

在上表中,我有消息,其中2个用户可以是发送者或接收者。

我需要从任一情况(例如:sender_userid到receiver_userid ..或.. receiver_userid到sender_userid)找到最重新发送的消息(来自一个用户ID 1000000172),我正在努力编写一个可以执行此操作的SELECT查询

您将在图像中看到两个用户ID(成员)已相互发送消息。如何选择最重要的一个。请记住,每个人之间都有很多信息。

我尝试了以下查询,但它会返回2条消息,其中用户是发件人和收件人:

SELECT sender_userid,receiver_userid,message,message_read,`datetime` 
FROM (
SELECT sender_userid,receiver_userid,message,message_read,`datetime` FROM messages 
WHERE (receiver_userid='1000000172' OR sender_userid='1000000172') AND friendship_status=1 AND receiver_history=1
ORDER BY message_read DESC, `datetime` DESC
) AS MSG
GROUP BY receiver_userid;

有没有办法只获得两个成员之间最重要的一条消息?

注意:我查询需要为此成员与其他成员获取许多消息 - 因此结果将是来自此用户的一条消息(最多重新发送),可能还有25个其他成员。


最终选择:

SELECT sender_userid,receiver_userid,message,message_read,`datetime` 
FROM (
SELECT sender_userid,receiver_userid,message,message_read,`datetime` FROM messages 
WHERE (receiver_userid='1000000172' OR sender_userid='1000000172') AND friendship_status=1 AND receiver_history=1
ORDER BY message_read DESC, `datetime` DESC
) AS MSG
GROUP BY (sender_userid AND receiver_userid);

2 个答案:

答案 0 :(得分:1)

尝试这样的事情: 按发件人和收件人分组,然后获得最大日期 -

select max(datetime) as time LIMIT 1
....
GROUP BY (sender_userid AND receiver_userid) ORDER BY datetime

答案 1 :(得分:0)

如果我理解你的问题,我猜你错了。

您接受的查询的工作原理

GROUP BY (sender_userid AND receiver_userid)

sender_userid AND receiver_userid是一个返回0或1的表达式,在您的情况下,它将返回1,因为所有id都大于0。

所以,你要查询如下

SELECT sender_userid,receiver_userid,message,message_read,`datetime` 
FROM (
   ...
) AS MSG
GROUP BY 1

前缀SQL无效,即使它适合您。

我的建议

我认为以下查询适合您。

SELECT '1000000172' AS my_id, sender_userid, receiver_userid,
  message, message_read, `datetime` AS dt
FROM messages
WHERE (receiver_userid='1000000172' OR sender_userid='1000000172')
    AND friendship_status = 1
    AND receiver_history = 1
ORDER BY dt DESC
LIMIT 1;
如果您有大量数据,

UNION可能会更好。即使col1 = xx OR col2 = xxcol1被索引,MySQL也无法在执行col2时使用INDEX。

SELECT *
FROM (
    SELECT '1000000172' AS my_id, sender_userid, receiver_userid,
      message, message_read, `datetime` AS dt
    FROM messages
    WHERE receiver_userid='1000000172'
        AND friendship_status = 1
        AND receiver_history = 1
    UNION ALL
    SELECT '1000000172' AS my_id, sender_userid, receiver_userid,
      message, message_read, `datetime` AS dt
    FROM messages
    WHERE sender_userid='1000000172')
        AND friendship_status = 1
        AND receiver_history = 1
) x
ORDER BY dt DESC
LIMIT 1