2011-09-22 79 views
0

我有一個欄目表1:SQL從一個表中選擇記錄,並以此作爲輸入到另一個表中刪除記錄

def_id, def_name, username etc 

我有有一些關聯的另一表表2:

assoc_id,parent_id,child_id 

parent_id,child_id實際上是來自Table1的def_id。它們基於GUI中的parent_child關係用戶操作被插入到表2中。

現在我想從Table1中爲特定用戶名選擇所有def_id,然後使用該輸入刪除所有記錄,如果這些def_ids是來自Table2的parent_id或child_id的一部分。

如何在SQL中執行此操作?我正在使用Sybase數據庫。

任何幫助將不勝感激

回答

2
Delete Table2 
Where parent_id In 
    (Select def_id from table1 
     Where username = @username) Or 
    child_id In 
    (Select def_id from table1 
     Where username = @username) 

或者

Delete t2 
    From table2 t2 
    Where Exists 
    (Select * From Table1 
     Where def_id In 
      (t2.parent_Id, t2.child_Id)) 
+0

感謝所有的答覆。真的非常感謝幫助我。查爾斯BRETANA的第一個答案的伎倆對我來說,他建議在下一個查詢給了我一個語法錯誤 SQL Anywhere錯誤-131:語法錯誤附近行「去哪兒」 1 感謝 -C – Chandu

+0

您可能需要添加從條款獲得第二個工作...我編輯顯示... –

0

一個簡單的方法是增加一個子查詢的WHERE子句。

DELETE ab 
FROM AuthorArticle AS ab 
WHERE ab.AuthID=(SELECT AuthID FROM Authors WHERE AuthorLastName='Yin') 

從未使用Sybase,但這是基本的SQL,應該可以工作。

0

嘗試:

DELETE table2 
FROM table2 
INNER JOIN table1 ON table1.def_id IN (table2.parent_id, table2.child_id) 
相關問題