Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

MYSQL basic conditional aggregation for same Columns

i have the following issue and i don't know how can i achieve that.

I need to filter based on both conditions + same property

Get Users where the event is "paymentFailed" and event is not "paymentSuccess"

  • Basically i need to filter all "Failed Payments" for every user, but the condition implies that a paymentSuccess must not exist for the same user.

  • If the paymentSuccess exists for the user, the result should be empty.

id  name    event             transaction_number    
2   John    paymentFailed         002   
3   John    paymentInProcess      003   
4   John    paymentStucked        004   
5   John    paymentSuccess        005   
6   Jane    paymentFailed         006   
7   Jane    paymentSuccess        007   
8   Reese   paymentFailed         008   
9   Reese   paymentFailed         009   
10  Reese   otherPayment          010   

Something like this (when paymentSuccess does not exists)

SELECT * FROM USERS where event != "paymentSuccess" AND event = "paymentFailed"

Result:

id  name    event             transaction_number    
8   Reese   paymentFailed         008   

And (when paymentSuccess exists)

SELECT * FROM USERS where event = "paymentSuccess" AND event = "paymentFailed"

Result:

id  name    event             transaction_number    
------------------------ Empty table -----------------------

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use NOT EXISTS:

SELECT u1.* 
FROM USERS u1 
WHERE u1.event = 'paymentFailed'
  AND NOT EXISTS (SELECT 1 FROM USERS u2 WHERE u2.name = u1.name AND u2.event = 'paymentSuccess')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...