Mysql selects a condition if another condition is not met

I have a table in which transactions are written. I want to select all identifiers that have exactly 4 transactions worth 2000, but then exclude those that have a single transaction 2500.

SELECT t.tuserid, COUNT(*) AS CNT
  FROM transactions t
 WHERE t.amt = 2000
 GROUP BY t.tuserid
 HAVING CNT = 4;

This part is simple enough, but I'm not sure how to effectively exclude anyone who has a transaction with t.amt = 2500. Would the simplest request for a where clause be the most efficient?

SELECT t.tuserid, COUNT(*) AS CNT
  FROM transactions t
 WHERE t.amt = 2000
 AND t.tuserid NOT IN (SELECT x.tuserid FROM transactions x WHERE x.amt=2500)
 GROUP BY t.tuserid
 HAVING CNT = 4;

The transaction table is large, and I'm not sure if a subquery is the most efficient way to start this process.

+4
source share
2 answers

, . "" , . "" .

.

, , where. O (log (n)), .

+3

, SUM

SELECT 
    t.tuserid, 
    SUM(CASE WHEN t.amt = 2000 THEN 1 ELSE 0 END CASE) AS CNT1, 
    SUM(CASE WHEN t.amt = 2500 THEN 1 ELSE 0 END CASE) AS CNT2
FROM 
    transactions t
GROUP BY 
    t.tuserid
HAVING 
    CNT1 = 4 AND CNT2 = 0;
0

Source: https://habr.com/ru/post/1690565/


All Articles