MySQL如何解决一对一关系

时间:2018-09-10 19:02:08

标签: mysql sql

我有一个与MySQL的一对一聊天实现。 目标是为一个用户提供最后一条消息的所有唯一对话。即使我在主键上使用MAX并按第二列对MySQL进行了拒绝。

以下查询给出错误:SELECT列表的表达式#2不在GROUP BY子句中,并且包含未聚合的列'm.id',该列在功能上不依赖于GROUP BY子句中的列;

我正在使用MySQL版本8。

我在这里缺少什么?

消息表

id | member_a_id | member_a_status | member_b_id | member_b_status | conversation_id | content | created_dt

会话表

id | member_a_id | member_a_status | member_b_id | member_b_status | conversation_id | content | created_dt | last_activity_dt

查询:

SELECT
  MAX(m.id) AS msgid, m.*
FROM
  message m
WHERE m.conversation_id IN
  (SELECT
    c.id
  FROM
    conversation c
  WHERE (
      c.member_a_id = 600
      AND c.member_a_status NOT IN (0, 3)
    )
    OR (
      c.member_b_id = 600
      AND c.member_b_status NOT IN (0, 3)
    ))
GROUP BY m.conversation_id
ORDER BY m.id DESC;

1 个答案:

答案 0 :(得分:2)

没有示例数据,您的问题将很难回答。但是,如果使用MySQL 8+,则应该使用窗口函数。查询如下所示:

SELECT cm.*
FROM (SELECT m.*,
             ROW_NUMBER() OVER (PARTITION BY m.conversation_id ORDE BY m.id DESC) as seqnum
      FROM message m JOIN
           conversion c
           ON m.conversation_id = c.conversation_id
      WHERE 600 IN (c.member_a_id, c.member_b_id) AND
            c.member_a_status NOT IN (0, 3)
     ) mc
WHERE seqnum = 1;