如何根据mysql中的一列获取唯一记录

时间:2014-03-01 10:08:12

标签: php mysql greatest-n-per-group

我有一张表格,其中多次使用subscription_id,每个月客户都会收取相同数据生成的订单。唯一的订单ID,所以有一个'updated_at'列也会更新,所以我想从基于subscription_id的表中获得一(1)条最新记录,我使用的是以下查询,但它不起作用并获得旧记录。

SELECT *
FROM members_subscriptions
WHERE status = 'active'
GROUP BY subscription_id
ORDER BY updated_at DESC

任何人都可以告诉我这个查询有什么问题......

4 个答案:

答案 0 :(得分:1)

您需要获取MAX()的{​​{1}},按分组运行排序,以便与最新日期进行比较

updated_at

SELECT DISTINCT *
FROM members_subscriptions
WHERE status = 'active'
AND updated_at IN(
SELECT MAX(updated_at) 
FROM members_subscriptions 
GROUP BY subscription_id
)
ORDER BY updated_at DESC

答案 1 :(得分:1)

假设每个子信息在updated_at中只能包含唯一日期,那么此查询应该会给出所需的结果:

SELECT *
FROM members_subscriptions
WHERE status = 'active'
AND (subscription_id, updated_at) IN(
    SELECT subscription_id, MAX(updated_at) 
    FROM members_subscriptions 
    GROUP BY subscription_id
)
ORDER BY updated_at DESC

但是,如果一个订阅的日期可能相同,那么查询必须使用唯一的id来获取两个或更多相同日期的一条记录:

SELECT *
FROM members_subscriptions m
WHERE status = 'active'
  AND id = (
      SELECT id FROM members_subscriptions m1
      WHERE m.subscription_id = m1.subscription_id
        AND status = 'active'
      ORDER BY updated_at DESC
      LIMIT 1
)

答案 2 :(得分:0)

您的查询存在的问题是,首先对结果进行分组,然后才对其进行排序。如果您需要最新结果,则需要执行以下操作:

SELECT *
   FROM members_subscriptions as main
   WHERE status = `active` AND `updated_at` = (
       SELECT MAX(`updated_at`) FROM members_subscriptions as sub
       WHERE status='active' and main.`subscription_id` = sub.`subscription_id`
   )

答案 3 :(得分:0)

SELECT distinct (name)
FROM members_subscriptions
WHERE status = 'active'
GROUP BY subscription_id
ORDER BY updated_at DESC

对您要查找的字段名称使用distinct