我有以下查询,其中查找计数:
stage_2 IS NULL stage_1等于1 member_group是5 按rel_id分组
至少有两行符合上述要求。
这很好用。它输出正确的结果6.(在我的小提琴中)。
SELECT COUNT(*) AS count_result
FROM (
SELECT sub.entry_id
FROM exp_judging AS jud
INNER JOIN exp_submissions AS sub ON jud.rel_id = sub.id
WHERE jud.stage_2 IS NULL
AND jud.stage_1 = 1
AND sub.member_group = 5
GROUP BY jud.rel_id
HAVING COUNT(*) >= 2
) AS a
问题在于,如果其中一个判断行已在'stage_2'中输入分数,则会继续计算此rel_id,因为在stage_2中仍有超过2行具有NULL。
我想要做的是检查以上所有内容是否正确,但是,对于stage_2,具有judge_id'14'的行为NULL。
我怎样才能做到这一点?
这是一个带有我的表和当前查询的SQL小提琴 - http://sqlfiddle.com/#!2/e5ee5/1
答案 0 :(得分:0)
考虑中间结果如下......
SELECT s.id
, s.member_group
, j.judge_id
, j.stage_1
, j.stage_2
FROM exp_judging j
JOIN exp_submissions s
ON s.id = j.rel_id
AND j.stage_1 = 1
AND s.member_group = 5
ORDER
BY j.rel_id
, j.judge_id;
+----+--------------+----------+---------+---------+
| id | member_group | judge_id | stage_1 | stage_2 |
+----+--------------+----------+---------+---------+
| 70 | 5 | 14 | 1 | 5 |<-- exclude because [14,5]
| 70 | 5 | 16 | 1 | NULL |<-- exclude because of [14,5] above
| 73 | 5 | 14 | 1 | 5 |<-- exclude because [14,5]
| 73 | 5 | 15 | 1 | NULL |<-- exclude because [14,5] above
| 73 | 5 | 16 | 1 | NULL |<-- exclude because [14,5] above
| 75 | 5 | 15 | 1 | NULL |
| 75 | 5 | 16 | 1 | NULL |
| 77 | 5 | 15 | 1 | NULL |
| 77 | 5 | 16 | 1 | NULL |
| 78 | 5 | 16 | 1 | NULL |
| 79 | 5 | 14 | 1 | NULL |
| 80 | 5 | 14 | 1 | NULL |
| 80 | 5 | 15 | 1 | NULL |
| 80 | 5 | 16 | 1 | NULL |
| 81 | 5 | 16 | 1 | NULL |
| 83 | 5 | 14 | 1 | NULL |
| 83 | 5 | 15 | 1 | NULL |
+----+--------------+----------+---------+---------+
要排除突出显示的行,我们可以执行此操作...
SELECT s.id
, s.member_group
, j.judge_id
, j.stage_1
, j.stage_2
FROM exp_judging j
JOIN exp_judging x
ON x.rel_id = j.rel_id
AND x.judge_id = 14
AND x.stage_2 IS NULL
JOIN exp_submissions s
ON s.id = j.rel_id
AND j.stage_1 = 1
AND s.member_group = 5
GROUP
BY j.rel_id
, j.judge_id;
+----+--------------+----------+---------+---------+
| id | member_group | judge_id | stage_1 | stage_2 |
+----+--------------+----------+---------+---------+
| 75 | 5 | 15 | 1 | NULL |
| 75 | 5 | 16 | 1 | NULL |
| 77 | 5 | 15 | 1 | NULL |
| 77 | 5 | 16 | 1 | NULL |
| 78 | 5 | 16 | 1 | NULL |
| 79 | 5 | 14 | 1 | NULL |
| 80 | 5 | 14 | 1 | NULL |
| 80 | 5 | 15 | 1 | NULL |
| 80 | 5 | 16 | 1 | NULL |
| 81 | 5 | 16 | 1 | NULL |
| 83 | 5 | 14 | 1 | NULL |
| 83 | 5 | 15 | 1 | NULL |
+----+--------------+----------+---------+---------+
从这里开始,剩下的步骤是微不足道的......
SELECT s.id
, COUNT(*)
FROM exp_judging j
JOIN exp_judging x
ON x.rel_id = j.rel_id
AND x.judge_id = 14
AND x.stage_2 IS NULL
JOIN exp_submissions s
ON s.id = j.rel_id
AND j.stage_1 = 1
AND s.member_group = 5
GROUP
BY j.rel_id;
+----+----------+
| id | COUNT(*) |
+----+----------+
| 75 | 2 |
| 77 | 2 |
| 78 | 1 |
| 79 | 1 |
| 80 | 3 |
| 81 | 1 |
| 83 | 2 |
+----+----------+