每组ID仅获得1个结果

时间:2019-01-16 09:36:00

标签: mysql

我有一个记录列表(domestic_helper_idcards),我希望每位工作人员(domestic_helper_id)仅退还一张未删除(is_deleted = 0)的卡,并且该卡具有card_expiration_date将来最远(最晚的到期日期)。

曾尝试分组等等,但无法使其正常工作。下面的代码:

SELECT * FROM domestic_helper_idcard
where
is_deleted = 0
order by card_expiration_date desc

这将返回以下(图像):

enter image description here

我只希望返回ID为4和5的记录。有人吗?

1 个答案:

答案 0 :(得分:1)

您可以对由domestic_helper_id分组的子查询使用具有聚合功能的联接,例如:max()

SELECT d.* 
FROM domestic_helper_idcard d
inner join (
  select domestic_helper_id, max(id) max_id
  from domestic_helper_idcard
  where  is_deleted = 0
  group by  domestic_helper_id 

) t on t.domestic_helper_id = d.domestic_helper_id and t.max_id  = d.id

order by d.card_expiration_date desc

并且按照Jens的建议,使用最大card_expiration_date进行澄清

SELECT d.* 
FROM domestic_helper_idcard d
inner join (
  select domestic_helper_id, max(card_expiration_date) max_date
  from domestic_helper_idcard
  where  is_deleted = 0
  group by  domestic_helper_id 

) t on t.domestic_helper_id = d.domestic_helper_id and t.max_date  = d.max_date

order by d.card_expiration_date desc