Question

I have a table in which subscription_id is used multiple times, every month a customer charged an order to be generated with same data & unique order id so there is a column 'updated_at' which also updates so I want to get only one (1) latest record from table based on subscription_id, I am using following query, but it's not working and getting old record.

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

Can any one tell me what's wrong with this query ....

Was it helpful?

Solution

You need get the MAX() of updated_at , order by runs after grouping so you need to compare with the newest date

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

or

SELECT DISTINCT m.* 
FROM members_subscriptions m 
INNER JOIN (
  SELECT subscription_id, MAX(updated_at) AS updated_at
  FROM members_subscriptions GROUP BY subscription_id
) AS maxdatte USING (subscription_id, updated_at);

OTHER TIPS

Assumming that each subsciption can have only unique dates in updated_at, then this query should give desired result:

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

But if one subscription may have more that one same dates, then the query must use unique id to get only one record from two or more with the same date:

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
)
SELECT distinct (name)
FROM members_subscriptions
WHERE status = 'active'
GROUP BY subscription_id
ORDER BY updated_at DESC

use distinct with field name you want to find

The problem with your query is that result is first being grouped and only then ordered. If you need latest result, you need to do something like this:

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`
   )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top