尝试使用SQL从多个表中删除

时间:2014-06-06 19:55:00

标签: sql oracle sql-delete

我的应用程序中有4个表:

  • 用户
  • USESSION
  • upklist
  • projshare

最后三个表包含一个名为session_id的字段。

在下面的代码中,括号中的部分用于从session_id表中获取用户“awpeople”的所有usession值。

问题是如何将此结果集读入数组并从数组结果中session_id的所有三个表中删除。

代码:

DELETE FROM usession, 
            upklist, 
            projshar 
WHERE  session_id = (SELECT session_id 
                     FROM   usession 
                     WHERE  delete_session_id IS NULL 
                            AND user_id = (SELECT user_id 
                                           FROM   users 
                                           WHERE  REGEXP_LIKE(USER_NAME, 
                                                  'awpeople', 'i'))); 

3 个答案:

答案 0 :(得分:1)

delete一次只能处理一个表格,因此您需要三个语句:

DELETE FROM upklist 
WHERE  session_id = (SELECT session_id 
                     FROM   usession 
                     WHERE  delete_session_id IS NULL 
                            AND user_id = (SELECT user_id 
                                           FROM   users 
                                           WHERE  REGEXP_LIKE(USER_NAME, 
                                                  'awpeople', 'i'))); 

DELETE FROM projshar 
WHERE  session_id = (SELECT session_id 
                     FROM   usession 
                     WHERE  delete_session_id IS NULL 
                            AND user_id = (SELECT user_id 
                                           FROM   users 
                                           WHERE  REGEXP_LIKE(USER_NAME, 
                                                  'awpeople', 'i'))); 

DELETE FROM usession 
WHERE  session_id = (SELECT session_id 
                     FROM   usession 
                     WHERE  delete_session_id IS NULL 
                            AND user_id = (SELECT user_id 
                                           FROM   users 
                                           WHERE  REGEXP_LIKE(USER_NAME, 
                                                  'awpeople', 'i'))); 

请注意,由于内部查询依赖于usersession,因此您应该从中删除最后

答案 1 :(得分:0)

如果usession在session_id上有唯一或主键,并且其他表具有外键关系,则可以从usession中删除该行,并让数据库将其级联到子表。

答案 2 :(得分:-2)

多表语法:

删除[LOW_PRIORITY] [QUICK] [IGNORE]     tbl_name [。] [,tbl_name [。]] ...     FROM table_references     [WHERE where_condition]

或者:

删除[LOW_PRIORITY] [QUICK] [IGNORE]     FROM tbl_name [。] [,tbl_name [。]] ...     使用table_references     [WHERE where_condition]

这来自oracle DELETE documentation