2012-07-12 113 views
0

我有以下查詢:SQL SELECT查詢到delete語句

select acc.Username from accounts acc 
left join accountevents ace on acc.accountid=ace.accountid 
left join leads lds on lds.leadid=acc.leadid 
where lds.DateEntered>'2011-01-01' and lds.DateEntered<'2011-02-01' 
Group by acc.Username 
Having count(ace.accounteventid)=0 

我想讓它DELETE語句:

delete username from accounts 
left join accountevents ace on accounts.accountid=ace.accountid 
left join leads lds on lds.leadid=accounts.leadid 
where Leads.DateEntered>'2011-01-01' and lds.DateEntered<'2011-02-01' 
Having count(accountevents.accounteventid)=0 

,我得到以下錯誤:附近的 語法不正確關鍵詞'有'。

有什麼建議嗎?

+2

**什麼是**數據庫系統,以及哪個版本? * SQL *只是*結構化查詢語言* - 許多數據庫系統使用的語言,但不是數據庫產品......這樣的功能通常是特定於供應商的 - 因此我們確實需要知道**數據庫系統**你正在使用...... – 2012-07-12 13:12:12

+0

你在刪除中取消了GROUP BY子句 - 你需要一個GROUP BY來使用HAVING,否則就使用'AND COUNT(Blah)= 0',count不會**要求**一個GROUP BY – Charleh 2012-07-12 13:13:47

回答

5

我想你應該重新寫了以下的方法:

delete from accounts where username in (<here goes your select statement>); 
0

來自SELECT查詢很明顯,表帳戶中的表accountevents和潛在客戶的關係。因此,首先必須從子表或外鍵表中刪除記錄,並從主表中刪除記錄。 如果您在數據庫設計或表格中設置了DELETE Rule to CASCADE,請運行此查詢。

DELETE FROM [TableName] where UserName ='UserName' -- TableName should be your primary table it may be Accounts or AccountsEvents or Leads 

並且如果您尚未在數據庫設計中設置DELETE規則,則必須運行三個查詢。首先從子表中刪除數據,然後從父表中刪除數據。

Delete from accounts where username = 'name' 
Delete from eventsaccounts where accountid = 'accountsid' 
Delete from leads where leadid = 'leadid'