【问题标题】:How to merge two generated tables using group by 'a' field by max of 'b' field?如何使用“a”字段按“b”字段的最大值合并两个生成的表?
【发布时间】:2012-05-30 01:12:25
【问题描述】:

有下一个查询:

select `privmsgs_id`, `contact`, `privmsgs_date`, `contentType` from (
    (
        select max(`privmsgs_id`) as `privmsgs_id`, `contact`, max(`privmsgs_date`) as `privmsgs_date`, `contentType` from (
            (
                select `privmsgs_from_userid` as `contact`, `privmsgs_id`, `privmsgs_date`, 'message' as `contentType`
                    from `privmsgs_table`
                where `privmsgs_to_userid` = 305026
            ) union (
                select `privmsgs_to_userid` as `contact`, `privmsgs_id`, `privmsgs_date`, 'message' as `contentType`
                    from `privmsgs_table`
                where `privmsgs_from_userid` = 305026
            )
        ) as `tmp` group by `contact` order by `privmsgs_date` desc
    ) union (
        select max(`privmsgs_id`) as `privmsgs_id`, `contact`, max(`privmsgs_date`) as `privmsgs_date`, `contentType` from (
            (
                select `from_userid` as `contact`, `id` as `privmsgs_id`, `date` as `privmsgs_date`, 'postcard' as `contentType`
                    from `postcards_table`
                where `to_userid` = 305026
            ) union (
                select `to_userid` as `contact`, `id` as `privmsgs_id`, `date` as `privmsgs_date`, 'postcard' as `contentType`
                    from `postcards_table`
                where `from_userid` = 305026
            )
        ) as `tmp1` group by `contact` order by `privmsgs_date` desc
    )
) as `rTmp` order by `privmsgs_date` desc;

有两个表tmptmp1被union合并,但是字段contact翻了一番:

privmsgs_id contact privmsgs_date   contentType
21490780    7070    1315207813      message
21556868    7070    1315215266      postcard
21226460    7754    1312025735      message
21539085    15588   1314615528      postcard
21489812    15588   1315208838      message

所以,我只需要最后一条记录(消息或明信片 - 无关紧要)和最后一条记录的 id(有问题 - 我可以在消息和明信片中分别获取 max(id),但不能这样做在合并表中):

privmsgs_id contact privmsgs_date   contentType
21556868    7070    1315215266      postcard
21226460    7754    1312025735      message
21489812    15588   1315208838      message

原因,我为什么不通过简化查询来做是因为我需要特定数量的结果,所以我只能通过一个查询来做到这一点。

【问题讨论】:

    标签: mysql sql merge group-by union


    【解决方案1】:

    您必须将结果按contact 分组并选择最大privmsgd_id,然后仅从privmsgd_id 中选择信息。

    查看GROUP BY了解更多信息。

    【讨论】:

    • 明信片和消息来自分开的表格,所以旧明信片的 id(按日期)可能小于早期的消息 id。有问题 - 我不能按不同的 id 对两个不同的表进行排序。
    • 我需要通过 contact 对记录进行分组并按 max(date) 排序来获取实际 ID。这是唯一的方法,但我不知道如何。
    猜你喜欢
    • 2014-01-30
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多