删除多表关联数据

删除多表关联数据
[ 2008-7-17 14:08:00 | By: 追忆逝水华年 ]
 

2008.04.15 以下的内容只是针对MySql数据库

1. sql语句删除两个或多个关联中的数据

    以前因为对数据库中的数据只是进行简单的操作,通常只是删除一个表中的数据(因为表与表中的关联性比较差,没有外键这样的约束),就像这样

delete 
from tableA a
where
1 = 1
and a.id
= 1 ;

delete后面不用指定表的名称,直到最近要删除两个表中的数据,表A与表B,表B中的内容是附属于表A的,也就是说如果表A中的某一条记录删除了,表B中的记录也要删除,因为如果不删除B中的记录,那就会形成垃圾数据,

表A中的一项为itemid,表B中也一个Column也为itemid,是以外键的形式指向表A.

当我这样写的时候就报错了:

delete 
from 
A a,
B b
where
1 = 1
and a.itemid
= b.itemid
and a.id
< 5

提示你where后的语句有问题(当然问题不在where语句),当from后面的表涉及到多个的时候,这个语句就要有点变化了

这样
delete 
a,b
from 
A a,B b
where
1 = 1
and a.itemid
= b.itemid
and a.id
< 5

或者是这样
delete 
from 
a,b
using  A a,B b
where
1 = 1
and a.itemid
= b.itemid
and a.id
< 5

from 中的表的名称没有先后顺序的要求,以下为<Sams - Mysql Tutorial(2003).chm>中的说明:

delete 语法:
DELETE   [ LOW_PRIORITY ]   [ QUICK ]   FROM  table_name
       
[ WHERE where_definition ]
       
[ ORDER BY ... ]
       
[ LIMIT rows ]

or

DELETE   [ LOW_PRIORITY ]   [ QUICK ]  table_name [ .* ]   [ , table_name[.* ]  ...]
       
FROM   table - references
       
[ WHERE where_definition ]

or

DELETE   [ LOW_PRIORITY ]   [ QUICK ]
       
FROM  table_name [ .* ]   [ , table_name[.* ]  ...]
       USING 
table - references
       
[ WHERE where_definition ]

示例代码为:

1 . 删除一个表中的数据
delete   from  department  where  name = ' Asset Management ' ;

2 . 删除两个表中的数据
delete  employee, employeeSkills
from  employee, employeeSkills, department
where  employee.employeeID  =  employeeSkills.employeeID
and  employee.departmentID  =  department.departmentID
and  department.name = ' Finance ' ;

3 . 删除两个表中的数据,用using语法
delete   from  employee, employeeSkills
using employee, employeeSkills, department
where  employee.employeeID  =  employeeSkills.employeeID
and  employee.departmentID  =  department.departmentID
and  department.name = ' Finance ' ;

转载于:https://www.cnblogs.com/China-Dragon/archive/2009/03/20/1417250.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值