实际场景中我们实现数据获取往往是多个表联合操作
eg: 从表group,user,user-group中获得每个分组的信息
自然连接
"select * from \"SOFTWARE\".\"user_group\" , \"SOFTWARE\".\"group\", \"SOFTWARE\".\"user\""
+ " where \"SOFTWARE\".\"group\" . \"id\" =? "
+ "AND "
+ " \"SOFTWARE\".\"user_group\" .\"group_id\"= \"SOFTWARE\".\"group\" .\"id\""
+ "AND"
+ "\"SOFTWARE\".\"user_group\" .\"user_id\"= \"SOFTWARE\".\"user\" .\"id\""
可以实现,但当user-group和user中没有与group绑定的数据时,即使存在group也查询为空。
左外连接
select * from "
+ " (\"SOFTWARE\".\"group\" left join \"SOFTWARE\".\"user_group\""
+ " on \"SOFTWARE\".\"group\" .\"id\"= \"SOFTWARE\".\"user_group\" .\"group_id\") "
+ " left join \"SOFTWARE\".\"user\" "
+ " on \"SOFTWARE\".\"user_group\" .\"user_id\"= \"SOFTWARE\".\"user\" .\"id\""
+ "where \"SOFTWARE\".\"group\" .\"id\"= ?"
解决问题,就算user-group和group中没有对应数据,左连接也会将左边的表group中内容输出,右连接同理
eg:删除一个分组以及这个分组下所有和用户的绑定关系
"delete \"SOFTWARE\".\"group\" , \"SOFTWARE\".\"user_group\" from "
+ " \"SOFTWARE\".\"group\" left join \"SOFTWARE\".\"user_group\""
+ " on \"SOFTWARE\".\"group\" .\"id\"= \"SOFTWARE\".\"user_group\" .\"group_id\" "
+ "where \"SOFTWARE\".\"group\" .\"id\"=?"
这个sql在mysql的环境下好用,oracle不行,oracle数据库不支持联合update和delete,为了实现一样的效果,提供两种解决方案
1.开启事务,在事务中对每个表单独delete
2.使用嵌套操作
delete from "
+ "("
+ "select 1 from \"SOFTWARE\".\"group\" left join \"SOFTWARE\".\"user_group\""
+ " on \"SOFTWARE\".\"group\" .\"id\"= \"SOFTWARE\".\"user_group\" .\"group_id\""
+ "where "
+ " \"SOFTWARE\".\"group\" .\"id\"=?"
+ ")"
ORA-01752: 不能从没有一个键值保存表的视图中删除