如何在不使用分组依据的情况下使用联接表获取唯一记录

时间:2019-02-11 11:47:25

标签: mysql sql database

我想从2个表中获取唯一记录而不使用Group By而不是我想使用DISTINCT,因为当我使用group by时,它不返回最近更新的记录。

我对分组依据使用了以下查询。

SELECT  au.id, o.order_id,o.payment_method, o.order_date,au.article_id FROM `orders` as o INNER JOIN austpost_api_response as au ON  o.order_id = au.order_id  where o.shipment_status = 1 AND au.active_status = 1 AND o.order_status = 0 group by o.order_id
ORDER BY `au`.`id`  DESC

它返回唯一的order_id,但没有得到最后更新的order_id

例如...

Order number 1212有四个article_id的ID 45,76,47,48,但是一旦我将其与group by一起使用,它将显示唯一的订单ID,但没有得到48个最后更新的记录,而不是返回45。

是否可以使用DISTINCT关键字。

2 个答案:

答案 0 :(得分:1)

如果您的mysql版本是8.0+,则可以使用row_number()函数。

select * from
(
SELECT  au.id, o.order_id,o.payment_method, o.order_date,au.article_id,row_number() over(partition by o.order_id order by o.order_date desc) as rn
FROM `orders` as o INNER JOIN austpost_api_response as au ON  o.order_id = au.order_id  where o.shipment_status = 1 AND au.active_status = 1 AND o.order_status = 0 
)A where rn=1

或者您可以尝试使用相关子查询

SELECT  au.id, o.order_id,o.payment_method, o.order_date,au.article_id
FROM `orders` as o INNER JOIN austpost_api_response as au ON  o.order_id = au.order_id  
where o.shipment_status = 1 AND au.active_status = 1 AND o.order_status = 0 and o.order_date in 
(
  select max(o.order_date) from `orders` o1 where o.order_id = o1.order_id and o1.order_status = 0
)

答案 1 :(得分:0)

如果我理解正确,则每个订单的响应都有多行-您希望每个订单都提供最新的行。

您要过滤数据,而不是汇总数据。我认为这可以满足您的要求:

SELECT au.id, o.order_id, o.payment_method, o.order_date, au.article_id
FROM orders o INNER JOIN
     austpost_api_response au
     ON o.order_id = au.order_id  
WHERE o.shipment_status = 1 AND
      au.active_status = 1 AND
      o.order_status = 0 AND
      au.id = (SELECT MAX(au2.id)
               FROM austpost_api_response au2
               WHERE au2.order_id = au.order_id AND
                     au2.active_status = 1
              )
ORDER BY au.id DESC;