MySql 使用遞迴函式時遇到的級聯刪除問題

2022-02-04 08:39:17 字數 2128 閱讀 4460

以下兩段sql的寫法看似相同,結果效果卻是不同的

寫法a

delete

om_organization,

om_position

from

om_organization

left

join om_position on om_position.org_id =

om_organization.org_id

where

find_in_set(

om_organization.org_id,om_organization_query_children(

'52037b7c-0f01-41f6-849f-4f99ad8f2422')

)

這個寫法是不正確的,先來介紹一下這個

om_organization_query_children
函式

begin

declare stemp varchar(4000

);declare stempchd varchar(4000

);set stemp ='$

';set stempchd =

id;

while stempchd is

notnull

doset stemp = concat(stemp,','

,stempchd);

select group_concat(org_id) into stempchd fromom_organizationwhere find_in_set(parent_org_id,stempchd)>0;

endwhile

;return

stemp;

end

id(varchar(40))是這個函式的引數

這個函式的執行結果是返回乙個拼起來的字串,字串根據主鍵org_id、父節點主鍵parent_org_id兩個字段,遞迴查詢出om_organization中所有以傳入引數作為根節點的主鍵,然後拼成乙個類似 【1,2,3,4】的可供find_in_set使用的字串(這裡定義成varchar(4000))。

寫法a中:每刪除一條資料都有可能造成om_organization_query_children ('1')

這個函式的執行結果變化,

假設刪除第一條的時候,這個函式的執行結果是【1,2,3】,其中』2『的父節點是』1『,』3『的父節點也是』1『,那麼在刪除完』2『之後,函式的結果變成了【1,3】,而後邊與』2『存在關係的om_position就無法被刪掉了。

正確的寫法應該如下:

寫法b:

delete

om_organization,

om_position

from

(

select

org_id

from

om_organization

where

find_in_set(

om_organization.org_id,

om_organization_query_children (

'52037b7c-0f01-41f6-849f-4f99ad8f2422')

)) t

inner

join om_organization on t.org_id =

om_organization.org_id

left

join om_position on om_position.org_id = om_organization.org_id

這樣,函式只執行一遍,其結果將一直保持不變,直到sql結束。不僅提高了效率,還避免了錯誤。

C語言 使用函式時遇到的問題

函式是一段 塊,由 返回型別 函式名 函式引數 構成。定義函式有兩種方式。一種是宣告與函式體放在一起,另一種是在main函式之前進行宣告,把函式塊放在 最後。我們通常使用後者 如下所示 include intfunction int a,int b int main intfunction int ...

在學習遞迴時遇到的問題

利用遞迴實現strlen 函式的功能int my strlen char arr 這段 乍一看好像是我們的思路,但是我沒有考慮到最重要的環節,當函式遞迴進入到最深層的時候 也就是字串被拆分完了以後只剩下乙個 0 的時候 我們的函式是沒有做任何的處理的,那麼這個函式的值為多少,我們是不知道的,我試著放...

使用ToluaFrameWork時遇到的一些問題

最近的專案在使用tolua框架熱更新。在做初期準備時,拿著github上的toluaframework進行學習和修改,在匯出安卓包時,遇到了一些問題,因此記錄了一下。1.plugins目錄下的x86和x86 64資料夾中的tolua要設定成不同的平台,android libs的armeabi v7a...