【分享】删除多个表中的关联记录
1. sql语句删除两个或多个关联中的数据
以前因为对数据库中的数据只是进行简单的操作,通常只是删除一个表中的数据(因为表与表中的关联性比较差,没有外键这样的约束),就像这样
delete
from tableA a
where
1=1
and a.id=1;
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
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
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]
[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';
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';
2. 有时候在页面中找一段文字是比较麻烦的一件事,特别是这个页面是动态生成的时候,如果是用的Eclipse的开发平台,可以用ctrl+H来开启查找界 面,可以查找某个类中的某个属性或者方法被那个地方调用了,也可以查找某个页面中包含要找的字段.如果应用部署在linux上,可以用grep "要查找的字段" /us***/doc/**.html ,其中"/us***/doc/**.html "为要查找的文件范围,可以用*来表示匹配任意的字符串,这样就可以限定查找的范围了,用这种查找命令来查找,还真是挺方便的.
阅读本文后,您的心情是:
恶心
愤怒
强赞
感动
路过
无聊
雷囧
关注