Mysql表“DemoTable”(id - >自动增量)
id subject_id subject_name question exams
1 3 sub3 ques1 e1,e4
2 3 sub3 ques2 e1
3 2 sub2 ques3 e1
4 2 sub2 ques4 e3,e5
我想要的是使用where where子句跟随输出 - where exams like '%e1%'
subject_id subject_name number_of_questions
3 sub3 2
2 sub2 1
目前,我正在使用两个单独的查询 -
获取主题名称列表 -
Select Distinct subject_id, subject_name from DemoTable where exams like '%e1%'
和
获得每个主题的问题数量 -
SELECT COUNT(*) as `num` FROM DemoTable where subject_id=$subject_id
但是对于我的工作,我需要一个查询同时执行这项工作,如上所述。 怎么做?
编辑 - 1.正如“juergen d”在他的回答中提到的那样 -
SELECT subject_id, subject_name, COUNT(distinct question) as questions_count
FROM DemoTable
where find_in_set('e1', exams) > 0
group by subject_id, subject_name
在此查询中find_in_set('e1', exams) > 0
有效,但仅作为exams='e1'
非exams like '%e1%'
,这是我的情况。
如何在like
中使用find_in_set
?
感谢。的问候,
答案 0 :(得分:2)
SELECT subject_id, subject_name, COUNT(distinct question) as questions_count
FROM DemoTable
where find_in_set('e1', exams) > 0
group by subject_id, subject_name