检查重复行尚不存在

时间:2013-10-04 07:41:32

标签: mysql sql

表格

exp_submissions
-----------------------------------------------------------------------------------
id | entry_id | member_id | member_group | category_id | type_id | portfolio_number
exp_judging
------------------------------------------------
id | rel_id | judge_id | pre | stage_1 | stage_2

目标:

  • exp_judging.rel_idexp_submissions.id
  • 上将两个表格加在一起
  • 仅选择以下行:
    • exp_submissions.member_group = 5exp_judging.pre = 1
    • judge_id != 1judge_id IS NULL
    • 现有的行没有相同的rel_idjudge_id = 1

以下查询执行到最后一部分的所有操作:

SELECT sub.entry_id 
FROM exp_judging AS jud
LEFT JOIN exp_submissions AS sub ON jud.rel_id = sub.id 
WHERE (jud.judge_id != 1 OR jud.judge_id IS NULL)
AND jud.pre = 1
AND sub.member_group = 5
LIMIT 1

这些是我在exp_judging表中的测试行:

enter image description here

正如您将看到的,有两行rel_id = 35(ID 200和197)。 上面的查询是选择行ID 197,即使有另一行具有相同的rel_id且具有judge_id = 1。这是我的问题。

我需要添加到我的查询中,检查没有其他行存在相同的rel_idjudge_id = 1,但我无法弄清楚如何。

谢谢。

1 个答案:

答案 0 :(得分:1)

您应该使用NOT EXISTS子句:

   SELECT sub.entry_id 
     FROM exp_judging AS jud
LEFT JOIN exp_submissions AS sub ON jud.rel_id = sub.id 
    WHERE (jud.judge_id != 1 OR jud.judge_id IS NULL)
      AND jud.pre = 1
      AND sub.member_group = 5
      AND NOT EXISTS (SELECT sub2.entry_id 
                        FROM exp_judging AS jud2
                   LEFT JOIN exp_submissions AS sub2 ON jud2.rel_id = sub2.id 
                       WHERE (jud2.judge_id = 1 )
                         AND jud2.pre = 1
                         AND sub2.member_group = 5
                         AND jud2.rel_id = jud.rel_id)
    LIMIT 1

编辑:添加了新条件