Shawn Wernig
Shawn Wernig

Reputation: 1742

MySQL - select row by user_id based on column value of other rows with the same user_id

I have a complicated request, so I have simplified it down, and hope I explain it well.

I have a table of Subscriptions:

ID   | Timestamp           | User Id | Status
-----+---------------------+---------+---------
1    | 2013-06-14 16:39:23 |    1    | inactive
2    | 2013-11-20 10:18:17 |    1    | active
3    | 2013-06-14 16:39:23 |    2    | inactive
4    | 2014-03-01 17:18:26 |    3    | active

I want to Query this table to find subscriptions which have a status of inactive, and who do NOT also have an active subscription.

For example, this should return Subscription ID 3, but not Subscription ID 1 - Because the User of ID 1 has an active subscription (being Subscription ID 2).

Upvotes: 0

Views: 993

Answers (2)

Iłya Bursov
Iłya Bursov

Reputation: 24146

following query should do the trick:

select a.id from
table as a
inner join
(
    select user_id, max(id)
    from table
    group by user_id
) as b
on (a.id=b.id and a.status='inactive')

Upvotes: 1

user2989408
user2989408

Reputation: 3137

Try the following and see if that works

SELECT *
FROM Table t
WHERE t.Status = 'inactive' 
    AND NOT EXISTS(SELECT 1 FROM Table t2 
                    WHERE t2.user_id = t.user_id 
                    AND t2.status <> 'inactive')

Upvotes: 0

Related Questions