mysql高级删除

时间:2010-06-29 17:15:03

标签: mysql

希望你能从下面的mysql查询中得到我想做的事情。

delete d1 from 
D as d1, D as d2
left join C rel1 on rel1.tld_tod_id=d1.did
left join C rel2 on rel2.tld_tod_id=d2.did
where d1.did!=d2.did and d1.name=d2.name
and rel1.cid is null and rel2.cid is not null
;

我在on子句中得到了未知的列d1.did, 我怎么做对了?

2 个答案:

答案 0 :(得分:1)

使用as用于列别名。对于表别名,只需将别名放在表格后面

delete d1 from 
D d1, D d2
left join C rel1 on rel1.tld_tod_id=d1.did
left join C rel2 on rel2.tld_tod_id=d2.did
where d1.did!=d2.did and d1.name=d2.name
and rel1.cid is null and rel2.cid is not null
;

如果我理解正确,如果它与表D无关,则会删除表C中具有重复名称的行。但是,如果是这样的话,连接不应该是OUTER吗?

答案 1 :(得分:0)

使用子选择:

DELETE FROM D AS D1 WHERE did IN (
  SELECT did FROM D as d1, D as d2
  LEFT JOIN C rel1 ON rel1.tld_tod_id=d1.did
  LEFT JOIN C rel2 ON rel2.tld_tod_id=d2.did
 WHERE d1.did!=d2.did AND d1.name=d2.name
 AND rel1.cid is null and rel2.cid is not null
)

SELECT查询返回一个id列表,该列表在DELETE语句中使用。 SELECT必须为每个要删除的记录选择一个字段。

这样做的一个优点是,您可以独立测试选择部分,以确保您选择正确的记录,然后将其插入删除声明。