Mysql

MySQL Where 子句細化 IF 連接存在

  • August 31, 2022

我有一個類似於下面的查詢。如果該記錄存在該行,我想為 RevisionBlast 添加一個條件。

select count(*)
from RevisionRun rr 
inner join RevisionForm rf on rf.id = rr.revisionformid
left outer join RevisionBlast rb on rb.RevisionRunId = rf.id
where rr.IsDeleted = 0 
 and rf.IsDeleted = 0;

我在想類似於下面的東西。我認為這可行,但我不確定這是否是處理此問題的最有效/最有效的方式。我假設這是一件很常見的事情,所以我只是想確保我做對了。

select count(*)
from RevisionRun rr 
inner join RevisionForm rf on rf.id = rr.revisionformid
left outer join RevisionBlast rb on rb.RevisionRunId = rf.id
where rr.IsDeleted = 0 
 and rf.IsDeleted = 0 
 and (IF(rb.IsDeleted is null or rb.IsDeleted = 0, 1, 0) = 1);

我會這樣寫:

select count(*)
from RevisionRun rr 
inner join RevisionForm rf on rf.id = rr.revisionformid
left outer join RevisionBlast rb on rb.RevisionRunId = rf.id
                               and rb.IsDeleted = 0
where rr.IsDeleted = 0 
 and rf.IsDeleted = 0;

即,將額外條件放入 的連接條件中rb。然後只有那些rb匹配額外條件的行才會滿足連接。

一個複合索引RrevisionBlast(RevisionRunId,IsDeleted)將有助於優化連接。

引用自:https://dba.stackexchange.com/questions/316290