MySQL计算所有行并计算所有行,其中field1 = 1

时间:2015-10-30 11:35:29

标签: mysql count

如何计算game_id = 1的所有行,并计算userid = 2在该game_id上​​的所有行= 1(1)

id    userid  game_id    hit    score    date
1     2       1          1      1        null
2     2       1          0      2        null
3     2       1          1      3        null
4     4       1          1      1        null
5     2       1          1      4        null
6     2       1          0      5        null
7     2       2          1      1        null

以及更多行

以上数据库信息 我们应该

game_id = 1的6行 和3用于userid = 2和hit = 1

返回的结果应为6,3

4 个答案:

答案 0 :(得分:2)

使用CASE表达式。

如果您希望每个计数位于不同的列中,请使用以下sql查询。

<强>查询

select 
    count(case game_id when 1 then 1 end) as count1,
    count(case when game_id = 1 and userid = 2 and hit = 1 then 1 end) as count2
from tblGame;

<强>输出

+--------+--------+
| count1 | count2 |
+--------+--------+
|      6 |      3 |
+--------+--------+

否则,如果您想将计数与逗号结合使用,请在查询中使用CONCAT

<强>查询

select concat(t.count1,', ',t.count2) as `count` from
(
  select 
      count(case game_id when 1 then 1 end) as count1,
      count(case when game_id = 1 and userid = 2 and hit = 1 then 1 end) as count2
  from tblGame
)t;

<强>输出

+-------+
| count |
+-------+
|  6, 3 |
+-------+

SQL Fiddle Demo

答案 1 :(得分:0)

使用MySQL count

select (select count(*) from table where where game_id = 1) as count1,
(select count(*) from table where userid = 2 and hit = 1) as count2
 from table limit 1

答案 2 :(得分:0)

试试这个MySQL查询: -

`SELECT COUNT(*) FROM db_table WHERE game_id = 1` 
and `SELECT COUNT(*) FROM db_table 
WHERE userid = 2 AND hit = 1`

答案 3 :(得分:0)

试试这个MySQL查询:

SELECT  COUNT(userid) as totalusers, (SELECT COUNT(*) FROM ForgeRock 
where game_id = 1 ) as totalgame FROM ForgeRock where game_id = 1 and
userid = 2 and hit = 1

SQL Fiddle