MySQL - 用不同的条件计算两件事

时间:2012-05-14 00:52:15

标签: mysql count

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

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

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

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

我知道我可以做到

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

然而,这只是一个计数,我需要将它们分开,这样我才能向用户显示更准确的信息。

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

4 个答案:

答案 0 :(得分:27)

简单地说:

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

答案 1 :(得分:7)

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 = ?

答案 2 :(得分: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

答案 3 :(得分:1)

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  |
|----+----+----+