【问题标题】:Returning the Max value of a half the composite key MYSQL返回组合键MYSQL的一半的最大值
【发布时间】:2020-08-24 13:12:23
【问题描述】:

我正在尝试查询具有由两个整数组成的复合键的表。关系是

我想要得到的结果是对于每个已经开始的对话,我想要消息表中的 MAX(threadNum)。目前查询是

SELECT c.conversation_id 
FROM conversation as c
INNER JOIN (
SELECT MAX(threadNum), user_from, user_to, message, dateTime, deleted,replied
FROM messages
GROUP BY conversation_id
) as m ON c.conversation_id = m.conversation_Id
WHERE (m.user_to ='$userId' OR m.user_from ='$userId') AND m.deleted = 0 

我期望的 conversation_Id 和 threadNum 的结果是: 35 5 34 4 33 55

每个 conversation_Id 一个结果,并且只有最大的 threadNum 结果。目前我得到一个 m.converation_Id 是一个未知的列。查询结构有什么问题?更重要的是,有没有更简单的方法来做我想做的事情?

【问题讨论】:

    标签: mysql sql database join greatest-n-per-group


    【解决方案1】:

    您似乎希望每个对话有一行,以及对话中的最新消息(即具有最大 thread_id 的消息)。

    如果是这样,那就是每组前 1 个问题。您可以通过使用相关子查询进行过滤来解决它:

    select c.*, m.*
    from conversation c
    inner join messages m on m.conversation_id = c.conversation_id
    where m.thread_num = (
        select max(m1.thread_num)
        from messages m1
        where 
            m1.conversation_id = m.conversation_id
            and m.deleted = 0
            and :user_id in (m.user_from, m.user_to)
    )
    

    :user_id 表示您的查询的查询参数(您应该使用参数化查询,而不是将变量混入查询字符串)。

    或者,如果您运行的是 MySQL 8.0,您可以使用row_number()

    select *
    from (
        select 
            c.*, 
            m.*, 
            row_number() over(partition by c.conversation order by m.thread_num desc) rn
        from conversation c
        inner join messages m on m.conversation_id = c.conversation_id
        where m.deleted = 0 and :user_id in (m.user_from, m.user_to)
    ) t
    where rn = 1
    

    【讨论】:

    • 谢谢。相关查询是这个项目让我感到沮丧的事情(php 课程中的学生项目超出了我对 sql 的了解)。我已将其集成并使其半工作,但仅返回 1 行。这是 threadNum 内部查询的 MAX 值。
    猜你喜欢
    • 2022-01-20
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2011-07-26
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    相关资源
    最近更新 更多