Chart JS的SQL查询

时间:2017-08-31 11:42:17

标签: php mysql database

我有这样一张桌子。

| id  | question_id | option_id |
---------------------------------
| 1   |         1   |         1 |
| 1   |         1   |         2 |
| 1   |         1   |         3 |
| 1   |         1   |         2 |
| 1   |         1   |         2 |
| 1   |         1   |         6 |

我如何查询结果如下?

[
  {'1' => 1},
  {'2' => 3},
  {'3' => 1},
  {'4' => 0},
  {'5' => 0},
  {'6' => 1},
]

目前我所拥有的是将查询从1循环到6.有没有办法在不知道可能的值(1到6)的情况下查询option_id的所有可能值的计数?

Select sum(case when option_id = 1 then 1 else 0 end) as "1" FROM fcs_answer WHERE question_id = 4;

2 个答案:

答案 0 :(得分:1)

有效查询可以是:

SELECT option_id, COUNT(*) FROM my_table GROUP BY option_id;

其他所有内容都可以在应用程序代码中处理

答案 1 :(得分:0)

尝试此查询。我认为这很有用

SELECT `option_id `,SUM(1) FROM table_name
GROUP BY `option_id `