有这样两张表,table2 中的 rid 关联 table1中的 id,t1 和 t2 是一对多的关系,没有做FK约束。本意是想执行delete table2 where rid in (select id from table1 where name='老大');
但在实际写的时候写成了。delete table2 where rid in (select rid from table1 where name='老大');
整句删除操作SQL按我理解来说,是有错误的,table1中没有rid这个字段,要么不能执行报错,要么是删除0行。
但意想不到的是,是删除了table2中的所有数据,不理解....拿出来讨论讨论

解决方案 »

  1.   

    因为子查询里面rid并没有跟子表有任何的关联关系,所以rid就是相当与一个常量,你的第二个sql跟
    delete table2 where rid =rid 是一样的
      

  2.   

    delete table2 where rid in (select rid from table1 where name='老大');
    等于
    delete table2 where rid in (select table2.rid from table1 where name='老大');
    所以不报错。
    而且在子查询中没有指定table1和table2的关联,所以子查询会返回table2.rid的全部记录,所以就删除了全部数据。
      

  3.   

    delete table2 where rid in (select rid from table1 where name='老大');其实你理解一下这个sql,相当于table2和table1进行关联,然后删除table2满足条件的数据,但子查询中没有关联条件,就把所有table1表的数据都查询出来了。至于你说的table1没有rid字段,你把这个子查询看成2个表关联就是了,rid还是从table2查询的。