Skip to content
Advertisement

MySQL multiple condition on same table

I have table “Transaction” with column

  • ID(primary)
  • Type (A or B)
  • Status (0 or 1)

I want to execute “SELECT * from Transaction WHERE type = ‘B’ and status = 0”, BUT this query can only return result if there is no Type “A” with status = 0. Is that possible to do that with one sql query?

Advertisement

Answer

You can use not exists:

SELECT * 
FROM Transaction t
WHERE type = 'B' and status = 0 AND
      NOT EXISTS (SELECT 1
                  FROM Transaction t2
                  WHERE type = 'A' AND status = 0
                 );

Note: Normally there would be a correlation clause which would connect to the subquery to the outer query.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement