有没有办法在最后一个子查询中包含IF语句(或者在其他地方,如果更合适的话),以排除 class_id IF 上计数的行在同一张表的考勤栏中对应 0 ?
我想要做的是,如果一个6人已经预订了一个班级(最大大小6),但是1个班级已经取消了 - 我希望结果为5,从而显示班级可用(为什么我依靠班级ID而非考勤领域)
SELECT c.*
FROM classes c
WHERE c.location_id = :location_id
AND (c.level_id = :current_level OR c.level_id = :previous_level OR c.level_id = :next_level)
AND c.datetime BETWEEN CURDATE() AND ADDDATE(CURDATE(),INTERVAL 14 DAY)
AND (c.class_id NOT IN (
SELECT class_id
FROM swimmer_classes)
OR c.class_id IN (
SELECT class_id
FROM swimmer_classes
GROUP BY class_id
HAVING COUNT(class_id) < 6))"
更新1
swimmer_classes schema
swimmer_class_id swimmer_id class_id attendance
1 1 1 null
2 2 1 null
3 3 1 null
4 4 1 null
5 5 1 null
6 6 1 0
结果:Count(class_id)= 6
所需输出
根据以下伪代码
计算所需数= 5 Count(class_id) - Count(attendance of class_id) = 5
答案 0 :(得分:1)
这样的事情会在你的场景中起作用吗?
SELECT class_id
FROM swimmer_classes
WHERE attendance <> 0 OR attendance is NULL
GROUP BY class_id
HAVING COUNT(class_id) < 6
或者更啰嗦:
SELECT class_id FROM
(
SELECT class_id, count(*) as cnt
FROM swimmer_classes
WHERE attendance <> 0 OR attendance is NULL
GROUP BY class_id
) t
where t.cnt < 6