场景
现有订单表,还有一张售后表,根据业务需求,现在是同一个订单会有多张售后单,通过获取最新的售后单来展示订单最新的售后信息
初始sql如下,但是这样没法去重,得到最新的售后信息
SELECT
a.id,
a.oid,
a.create_time AS apply_time,
o.order_num,
o.aftersale_id
FROM
mall_shop_order_aftersale AS a
LEFT JOIN mall_shop_order AS o ON a.oid = o.id
第一个想到的就是通过distinct关键字来去重,但是在这里distinct是不生效的,因为distinct只能用在select查询字段的开头,表示后面所有查询字段的都不重复才算不重复,这里有查询的字段有很多,sql中只列举3~5个,是没法去重的,所以想到通过子查询先去重售后单再关联表,sql如下
SELECT
a.id,
a.oid,
a.create_time AS apply_time,
o.order_num,
o.aftersale_id
FROM
mall_shop_order_aftersale AS a
JOIN ( SELECT oid, max( create_time ) mtime FROM mall_shop_order_aftersale GROUP BY oid ) t ON a.oid = t.oid
AND a.create_time = t.mtime
LEFT JOIN mall_shop_order AS o ON a.oid = o.id
其实,完全可以在订单表中关联一个最新售后单Id,也可解决
SELECT
a.id,
a.oid,
a.create_time AS apply_time,
o.order_num,
o.aftersale_id
FROM
mall_shop_order o
LEFT JOIN mall_shop_order_aftersale AS a on o.aftersale_id = a.id
where o.aftersale_id > 0