标签:MySQL 、删除数据、踩坑
在工作中遇到这样一种情况。数据库中有两个表:用户表和课程表,两个表通过u_id关联,但是没有建外键:
t_user |
u_id |
u_name |
u_age |
t_cause |
c_id |
c_name |
u_id |
调皮的课程表中被人写了很多数据,并且用户是存在的。如何删除这些垃圾数据?
1、先删除数据;
1.1、先查询到底有多少数据,轻松得到sql
select * from t_casue t where not exists (select 1 from t_user u where u.u_id=t.u_id );
1.2、再删除数据,心想这没什么难度啊,只要把select 改成delete 就可以了;
delete * from t_casue t where not exists (select 1 from t_user u where u.u_id=t.u_id );
万万没想到,报错了???我记得在oracle 数据库中就是这么用的啊!报的错是1064语法错误。
1.3、解决问题的思路:
1.3.1、通过外链接来实现删除,但是我个人很讨厌写left join on 和right join on ;
1.3.2、不用数据库的昵称,sql 如下:
delete * from t_casue t where not exists (select 1 from t_user u where u.u_id=t_cause.u_id );
2、建立外键,保证数据的完整性。
个人总结:
1、凡是涉及到表管理的,尽量要使用外键,这样可以保证数据的完整性;
2、不同的数据库之间有不同的语法,会有不同的细节