你能用两个带连接的嵌入式选择来改进mysql更新吗?

时间:2016-08-22 14:55:36

标签: mysql

我在此查询中使用了3个表:

  1. 讲师(包含"软"已删除的专栏)
  2. school(包含" soft"已删除的专栏)
  3. instructor_school(讲师和学校之间的关联表)
  4. 如果学校被标记为已删除,我希望该学校的教师也被标记为已删除,但 。这是我提出的查询:

    Function test_zeroSQL()
    
    Dim nsemaine As Single
    Dim var11 As Single
    Dim var50 As Single
    Dim var60 As Single
    Dim var11b As Single
    Dim var50b As Single
    Dim var60b As Single
    
    nsemaine = DatePart("ww", Date, 2, 2) - 1
    If zero11() = 0 Then
        var11 = 1
        var11b = 1
    Else
        var11 = zero11()
        var11b = zero11b()
    End If
    
    If zero50() = 0 Then
        var50 = 1
        var50b = 1
    Else
        var50 = zero50()
        var50b = zero50b()
    End If
    
    If zero60() = 0 Then
        var60 = 1
        var60b = 1
    Else
        var60 = zero60()
        var60b = zero60b()
    End If
    
    test_zeroSQL = "INSERT INTO [Taux de Service] ( Semaine, [Sortie B60], [Nc B60], [Sortie B50], [Nc B50], [Sortie B11], [Nc B11] )"
    test_zeroSQL = test_zeroSQL & vbCrLf & "VALUES (" & nsemaine & "," & var60 & "," & var60b & "," & var50 & "," & var50b & "," & var11 & " ," & var11b & " )"
    End Function
    

    如果我们只允许每个教师在一所学校,那么查询会更简单:

    update instructor as i
    set deleted=1
    where
    (select count(*) from instructor_school as i_s join school s
     on s.id=i_s.school_id
     where i_s.instructor_id=i.id) = 
    (select count(*) from instructor_school as i_s join school s
     on s.id=i_s.school_id
     where i_s.instructor_id=i.id and s.deleted=1);
    

    我的问题是 - 此查询是解决此问题的最佳方法 - 或者您能建议更好的查询吗?

    感谢您的任何建议!

1 个答案:

答案 0 :(得分:2)

UPDATE instructor AS i
JOIN instructor_school i_s_deleted ON i.id = i_s_deleted.instructor_id
JOIN school s_deleted ON i_s_deleted.school_id = s_deleted.id AND s_deleted.deleted = 1
LEFT JOIN instructor_school AS i_s_active 
    JOIN school s_active ON i_s_active.school_id = s_active.id AND s_active.deleted <> 1
ON i.id = i_s_active.instructor_id 
SET i.deleted=1
WHERE i_s_active.school_id IS NULL;

我在这里所做的是首先我加入了instructor_school和学校,以确保有一所学校被删除。然后我再次加入了instructor_school和学校作为活动,然后我把i_s_active.school_id为null放在我的where子句中。这将确保教师不与任何活跃的学校相关联。

希望这有帮助!