如何获取mysql中重复行的数量

时间:2014-06-13 12:42:31

标签: mysql sql

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

感谢。的问候,

1 个答案:

答案 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