SQL select查询到delete语句

时间:2012-07-12 13:10:39

标签: sql

我有以下查询:

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 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

我收到以下错误: 关键字'Having'附近的语法不正确。

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

我认为你应该按照以下方式重写它:

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

答案 1 :(得分:0)

从select查询中可以看出,表帐户与表accountevents和lead有关系。因此,首先必须从子表或外键表以及主表中删除记录。 如果您在数据库设计或表中设置了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'