问题
I want to count two things under different conditions in one query.
SELECT COUNT(*) AS count FROM table_name WHERE name = ?
and
SELECT COUNT(*) as count FROM table_name WHERE address = ? AND port = ?
I need to have a count for rows that have a certain address and certain port, and a SEPARATE count for rows that have a certain name.
I'm aware that I could do
SELECT (COUNT*) as count FROM table_name WHERE (address = ? AND port = ?) OR name = ?
However that is a single count, and I need them to be separate so I can display a more accurate message to the user.
How might I go about doing this? Help would be appreciated!
回答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
回答2:
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 = ?
回答3:
Might be easiest just to do a Union:
SELECT COUNT(*) AS count FROM table_name WHERE name = ?
GROUP BY name
UNION ALL
SELECT COUNT(*) as count FROM table_name WHERE address = ? AND port = ?
GROUP BY address, port
回答4:
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 |
|----+----+----+
来源:https://stackoverflow.com/questions/10576435/mysql-counting-two-things-with-different-conditions