简体   繁体   English

需要我的 mysql 表结果在 2 条件下的结果的一些解决方案

[英]Need some solution for result of my mysql table result in 2 condition

I have table like this我有这样的桌子

table_name : AnswerDetail

|id_session|id_question|value|
------------------------------
|1         |1          |4    |
|1         |2          |4    |
|1         |3          |4    |
|1         |4          |2    |
|1         |1          |3    |
|1         |2          |2    |
|1         |3          |1    |
|1         |4          |4    |
|2         |1          |3    |
|2         |2          |2    |
|2         |3          |2    |
|3         |1          |4    |

I need show some result by 2 condition here,我需要在这里通过 2 个条件显示一些结果,

$query = $this->db->query("SELECT a.id_session, a.id_question,
(SELECT COUNT(*) FROM AnswerDetail WHERE id_session=1 AND value=4 AND id_question=1) AS great,
(SELECT COUNT(*) FROM AnswerDetail WHERE id_session=1 AND value=3 AND id_question=1) AS good"),
(SELECT COUNT(*) FROM AnswerDetail WHERE id_session=1 AND value=2 AND id_question=1) AS not bad
FROM (SELECT DISTINCT id_session,id_question FROM AnswerDetail) a WHERE id_session=1);

what i need to do here is, im put id_session by ID from URL SEGMENT (its ok),but id_question by an array by looping from foreach php.我需要在这里做的是,我将id_session按 ID 从 URL SEGMENT (它可以),但通过从 foreach id_question循环的数组中输入 id_question。

and thats query just show by id_question=1 , how can i get result by id_question by [1,2,3,4]那就是查询仅由id_question=1显示,我如何id_question by [1,2,3,4]结果

what im expected is actual like this我所期望的实际上是这样的

|id_session|id_question|great|good|not bad|
-------------------------------------------
|1         |1          |1    |1   |0      |
|1         |2          |1    |0   |1      |
|1         |3          |1    |0   |0      |
|1         |4          |1    |0   |1      |

any solution?任何解决方案? or what should i change?或者我应该改变什么?

you can use sum() instead of count() then group by session and question ids.您可以使用sum()而不是count()然后按sessionquestion ID 分组。

select id_session, id_question, sum(case when value = 4 then 1 else 0 end) as great,
    sum(case when value = 3 then 1 else 0 end) as good,
    sum(case when value = 2 then 1 else 0 end) as notbad
from AnswerDetail
where id_session = 1
group by id_session, id_question

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM