22

我想在一个查询中计算不同条件下的两件事。

SELECT COUNT(*) AS count FROM table_name WHERE name = ?

SELECT COUNT(*) as count FROM table_name WHERE address = ? AND port = ?

我需要对具有特定地址和特定端口的行进行计数,对具有特定名称的行进行单独计数。

我知道我可以做到

SELECT (COUNT*) as count FROM table_name WHERE (address = ? AND port = ?) OR name = ?

然而,这是一个单一的计数,我需要将它们分开,以便我可以向用户显示更准确的消息。

我该怎么做呢?帮助将不胜感激!

4

4 回答 4

42

简单地说:

SELECT 
    SUM(IF(name = ?, 1, 0)) AS name_count,
    SUM(IF(address = ? AND port = ?, 1, 0)) AS addr_count
FROM 
    table_name
于 2012-05-14T01:08:56.227 回答
9
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 = ?
于 2012-05-14T01:00:27.207 回答
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

使用COUNT(CASE...),您可以从单个表中获取两列的计数,即使两者的条件不同(例如:从 n1 列获取 J 的计数,从 n2 列获取 C 的计数,等等..)

表:测试

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

结果:

+----+----+----+
| t1 | t2 | t3 |
|----+----+----+
|  3 | 2  | 1  |
|----+----+----+
于 2019-10-04T10:56:36.737 回答
2

做一个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
于 2012-05-14T01:00:34.980 回答