mysql - 如何使用 group by 'a' field by max of 'b' field 合并两个生成的表?

标签 mysql sql merge group-by union

有下一个查询:

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

之所以不通过简化查询来实现,是因为我需要特定数量的结果,所以,我只能通过一个查询来实现。

最佳答案

您必须按contact 对结果进行分组并选择最大的privmsgd_id,然后仅从那些privmsgd_id 中选择信息。

检查 GROUP BY了解更多信息。

关于mysql - 如何使用 group by 'a' field by max of 'b' field 合并两个生成的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10720772/

相关文章:

mysql - 使用表别名的 SQL 查询

mysql - 需要一些帮助从查询中取回表,以便将来在我自己的数据库中使用

sql - Rodbc 日期过滤器

mysql - SQL 土耳其语语言显示问题

mysql - MYSQL将一张表中的所有列插入到另一张表中

javascript - 合并两个数组,使值交替

java - 如何将 Class< 类型的值存储到数据库?使用 Hibernate 扩展 View>

mysql - 使用 Qt 连接数据库 : Failed?

sql - 使用 SQL 计算列中的项目数

git - 线尾: Git merge creates duplicates without conflict