当前位置: 代码迷 >> Sql Server >> SQL级联查询有关问题
  详细解决方案

SQL级联查询有关问题

热度:150   发布时间:2016-04-27 14:11:50.0
SQL级联查询问题
我需要将下面三个SQL语句整合成一个SQL语句 用来删除数据

SQL code
--第一级 select ciid from communityinfor as Community where parent!=0 and parent not in (select ciid from communityinfor )--第二级select ciid from communityinfor where parent in (select ciid from communityinfor as Community where parent!=0 and parent not in (select ciid from communityinfor ))--第三级select ciid from communityinfor where parent in(select ciid from communityinfor where parent in (select ciid from communityinfor as Community where parent!=0 and parent not in (select ciid from communityinfor )))

请问我该如何做。。

以下是我的数据库表字段

SQL code
/*==============================================================*//* Table: communityinfor                                        *//*==============================================================*/create table communityinfor (   ciid                 int                  identity,   levelid              int                  not null,   parent               int                  not null,   communityname        varchar(50)          not null,   constraint pk_communityinfor primary key (ciid))godeclare @currentuser sysnameselect @currentuser = user_name()execute sp_addextendedproperty 'MS_Description',    '小区信息   需要具体到室   页面需要树控件显示出小区的所有信息。 从小区到室。 所有节点的信息   1.CIID ID   2.LevelID    级别信息外键ID[LevelInfor]表的外键。指示该节点所属的级别      4.Parent      父级。例如 1单元,它所属的栋级 是哪个 ?此字段引用自己的主键   5.CommunityName      节点的完整名称。  例如一栋一单元, 或者一栋一单元0101室   ',   'user', @currentuser, 'table', 'communityinfor'go




------解决方案--------------------
建主外键,设级联删。
------解决方案--------------------
1、建表时加主外键约束,加 CASCADE DELETE --即 级联删除
2、或者建DML的删除触发器
------解决方案--------------------
探讨

引用:
1、建表时加主外键约束,加 CASCADE DELETE --即 级联删除
2、或者建DML的删除触发器


谢谢 这个可以。 但我还想问下。 如果我想要用SQL语句删除这些冗余数据的话 该怎么写这条SQL语句呢?

------解决方案--------------------
将你查询的三个ciid的结果集union起来,然后直接按这个来删除。
  相关解决方案