我在mysql中有一个学生月度表 我在records_day栏中记录了每月1,2,3,4,5,6..31的每一天。与数学,科学,英语等主题明智。等
月表如:
subject recorded_day
Math 1
science 1
English 1
Math 2
science 2
English 2
Math 4
science 4
English 4
Math 7
science 8
English 9
如何编写查询以检索在课堂上不存在的数据分离的主题学生。 我想要检索录制的日期哪个学生不在主题明确的班级
输出
subject recorded_day not present
Math 3,5,6,8,9,10...31
science 3,5,6,7,9......31
English 3,5,6,7,8,10,...31
答案 0 :(得分:0)
试试这个:
SELECT t.Subject, GROUP_CONCAT(t.row order by t.row)
FROM
(
SELECT row, subject
FROM
(
SELECT @row := @row + 1 as row FROM
(select 0 union all select 1 union all select 3 union all
select 4 union all select 5 union all select 6 ) t,
(select 0 union all select 1 union all select 3 union all
select 4 union all select 5 union all select 6 ) t2,
(SELECT @row:=0) AS t3
) as sub,
(
SELECT 'Math' AS subject UNION ALL SELECT 'science'
UNION ALL SELECT 'English') AS subjects
WHERE row <= 31
) AS t
LEFT JOIN Table1 AS t1
ON t.row = t1.recorded_day AND t.subject = t1.subject
WHERE t1.recorded_day IS NULL
GROUP BY t.subject;
以下是它的工作原理:
LEFT JOIN
原始表格,以获取那些不存在的日子。GROUP_CONCAT
与GROUP BY
一起使用。结果:
| Subject | NotPresent
|---------|-----------------------------------------------------------------------------|
| English | 3,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 |
| Math | 3,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 |
| science | 3,5,6,7,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 |
答案 1 :(得分:-1)
您需要创建一个包含几天和所有主题的表格(month_days):
days subject
1 Math
2 Math
3 Math
.
.
.
31(or 30, 28, 29) English
1 English
2 English
3 English
.
.
.
31(or 30, 28, 29) English
.
.
SELECT subject, GROUP_CONCAT(recorded_day SEPARATOR ',')
FROM month_days m_d
LEFT JOIN table t on t.recorded_day=m_d.days and t.subject=m_d.subject
WHERE t.recorded_day is null
GROUP BY subject;