mybatis去重小结

在开发中遇到需要记录用户的所有浏览商品记录,但是返回前端记录中需要对重复店铺的重复商品进行去重处理,刚开始使用了distinct,发现返回结果只有product_id,shop_id,shop_type这三个字段有值,其他字段均为null;

 Wrapper<TbUserFootprint> wr = new EntityWrapper<>();
        wr.  setSqlSelect("distinct product_id,shop_id,shop_type")
                .eq("user_id", userId)
                .eq("product_type", productType)
                .eq("del_flag", CommonConstant.STATUS_NORMAL)
                .orderBy("create_time", false)
   List<TbUserFootprint> tbUserFootprintList = this.baseMapper.selectList(wr);

后改用groupBy关键字来处理,具体如下:

      wr .eq("user_id", userId)
                .eq("product_type", productType)
                .eq("del_flag", CommonConstant.STATUS_NORMAL)
              .groupBy("product_id,shop_id,shop_type");
        List<TbUserFootprint> tbUserFootprintList = this.baseMapper.selectList(wr);

总结:在去重查询时,distinct关键字只能返回它的目标字段,而无法同时返回其它字段,要想解决这个问题,可以利用group by按照多列进行嵌套分组。

发布了26 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42643690/article/details/103802010