我有下表,我想选择在 12 月而非 1 月进行过交易的每个 user_id。
User_Id |Month |Transaction_Id |Transaction_Amount
------------------------------------------------------------
1 |Dec |50 |452.36
1 |Jan |51 |963.2
3 |Dec |52 |499.3
4 |Jan |53 |156.85
1 |Dec |54 |145.63
3 |Dec |55 |20.99
执行查询后,该表应如下所示:
User_Id |Month |Transaction_Id |Transaction_Amount
------------------------------------------------------------
3 |Dec |52 |499.3
3 |Dec |55 |20.99
请注意,我需要使用一个高效的查询来过滤上述要求,因为这将应用于数千条记录。
最佳答案
有几种方法:
使用不存在:
select * from yourtable t
where month = 'Dec'
and NOT EXISTS (
select null from yourtable t2
where t2.user_id = t.user_id
and t2.month = 'Jan')
使用 NOT IN()
select * from yourtable t
where month = 'Dec'
and user_id NOT IN (
select t2.user_id from yourtable t2
where t2.month = 'Jan')
使用左连接:
select t.* from yourtable t
left join yourtable t2 on t2.user_id = t.user_id and t2.month = 'Jan'
where t.month = 'Dec'
and t2.user_id IS NULL
关于mysql - 检索 User_ID 在 12 月而非 1 月进行交易的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521611/