MySQL - Counting two things with different conditions

SELECT 
  COUNT( CASE WHEN n1 = 'J' THEN 1 END ) AS t1,
  COUNT( CASE WHEN n2 = 'C' THEN 1 END ) AS t2,
  COUNT( CASE WHEN n3 = 'K' THEN 1 END ) AS t3 
FROM test

Using COUNT(CASE...), you can get the count of two-column from single table, even when conditions for both are different (eg: Get count of J from n1 column and count of C from n2 column, and so on..)

Table: test

+----+----+----+----+
| id | n1 | n2 | n3 |
|----+----+----+----+
|  1 | J  | C  | K  |
|----+----+----+----+
|  1 | J  | C  | F  |
|----+----+----+----+
|  1 | J  | K  | C  |
|----+----+----+----+
|  1 | K  | K  | C  |
|----+----+----+----+

Result:

+----+----+----+
| t1 | t2 | t3 |
|----+----+----+
|  3 | 2  | 1  |
|----+----+----+

What about simply:

SELECT 
    SUM(IF(name = ?, 1, 0)) AS name_count,
    SUM(IF(address = ? AND port = ?, 1, 0)) AS addr_count
FROM 
    table_name

SELECT SUM(CASE WHEN Name = ? THEN 1 ELSE 0 END) as name_match
       , SUM(CASE WHEN Address = ? AND Port = ? THEN 1 ELSE 0 END) as address_match
FROM table_name
WHERE (address = ? AND port = ?) OR name = ?

Tags:

Mysql

Count