简体   繁体   中英

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).

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')

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM