【问题标题】:how to pull unique results如何提取独特的结果
【发布时间】:2011-06-10 13:35:48
【问题描述】:

我正在寻找查询来加载和分组数据

我确实有 1:n 的 Parent:Child 关系

我想拉父母的最新孩子,而不是孩子

这意味着每个条目都应该有唯一的父级和最新的子级。

子表

期望的结果

试过了:

我尝试了以下查询,但它得到了最旧的结果

SELECT c.* FROM child  AS c GROUP BY c.parent_id HAVING(MAX(c.order))

提前致谢

【问题讨论】:

    标签: sql mysql hibernate


    【解决方案1】:
    select ct.*
        from ChildTable ct
            inner join (select parent_id, max(order) as MaxOrder
                            from ChildTable
                            group by parent_id) q
                on ct.parent_id = q.parent_id
                    and ct.order= q.MaxOrder
    

    【讨论】:

    • 很抱歉,它不起作用,因为它让我超过 2 行。必须有两行
    • 如果显示正确的结果,请将ORDER BY ct.createdDate LIMIT 1 添加到查询的末尾,这样就可以满足您的需要
    • @Rehman:您希望如何解决关系,例如createdDate 对于parent_id 2 的所有4 个条目都相同的情况?
    • @Joe:好的,我接受 parent2 的子表中的 createdDate 与 parent_1 相同。让我再给你发一张更改日期的图片。
    • @Rehman:所以,当你说你想要“最新”的孩子时,看起来你想基于 order 列而不是我的 createdDate 列来定义“最新”用过的。对吗?
    猜你喜欢
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    相关资源
    最近更新 更多