有没有一种方法可以计算MySQL中JSON列的元素?

时间:2019-07-25 16:54:00

标签: mysql

我有下表answers对应于每个新提交的调查。

enter image description here

我想得到的结果是:

| rst_id | school_id | q_4_1 | q_4_2 | ... | q_4_43 |
+--------+-----------+-------+-------+-----+--------+
|      9 |       101 |     3 |     0 | ... |      3 |

在MySQL 5.8中甚至可能吗?

相同的问题:Count occurrences of items in a MySQL JSON field

1 个答案:

答案 0 :(得分:0)

这是一种适合可能需要它的人使用的解决方案。

SELECT
    answers.id,
    schools.id,
    schools.name,
    regional_sports_trust.id,
    regional_sports_trust.name,
    SUM(INSTR(q_4, '"0"') > 0) as q_4_answer_0_count,
    SUM(INSTR(q_4, '"1"') > 0) as q_4_answer_1_count,
    SUM(INSTR(q_4, '"2"') > 0) as q_4_answer_2_count,
    ...
    SUM(INSTR(q_4, '"69"') > 0) as q_4_answer_69_count,
    COUNT(*) AS total_count
FROM
    `answers`
LEFT JOIN regional_sports_trust ON regional_sports_trust.id = answers.rst_id
LEFT JOIN schools ON schools.id = answers.school_id