sqlserver delete 关联条件删除

-- 创建t1表,并插入3条数据
CREATE TABLE [dbo].[t1] ([id] [INT] NOT NULL, [name] [NCHAR](10) NULL) ON [PRIMARY];
GO
INSERT INTO dbo.t1(id, name)
VALUES(1, -- id - int
N'lisi' -- name - nchar(10)
    );

INSERT INTO dbo.t1(id, name)
VALUES(2, -- id - int
N'zhangsan' -- name - nchar(10)
    );


INSERT INTO dbo.t1(id, name)
VALUES(3, -- id - int
N'aben' -- name - nchar(10)
    );

-- 创建t2表,并插入2条数据
CREATE TABLE [dbo].[t2] ([id] [INT] NOT NULL, [name] [NCHAR](10) NULL) ON [PRIMARY];
GO
INSERT INTO dbo.t2(id, name)
VALUES(1, -- id - int
N'lisi' -- name - nchar(10)
    );

INSERT INTO dbo.t2(id, name)
VALUES(2, -- id - int
N'zhangsan' -- name - nchar(10)
    );



SELECT * FROM dbo.t1;

SELECT * FROM dbo.t2;

SELECT b.* FROM t1 AS a INNER JOIN t2 AS b ON a.id=b.id;


-- 删除内关联t1表后的2条记录
DELETE t1 FROM t1 AS a INNER JOIN t2 AS b ON a.id=b.id;

-- 删除内关联t2表后的2条记录
DELETE t2 FROM t1 AS a INNER JOIN t2 AS b ON a.id=b.id;



SELECT b.* FROM t1 AS a LEFT JOIN t2 AS b ON a.id=b.id;

-- 删除左外关联后的t1表3条记录
DELETE t1 FROM t1 AS a LEFT JOIN t2 AS b ON a.id=b.id;

-- 删除左外关联后的t2表2条记录
DELETE t2 FROM t1 AS a LEFT JOIN t2 AS b ON a.id=b.id;

 

posted @ 2021-09-01 20:39  跟着阿笨一起玩.NET  阅读(1726)  评论(0编辑  收藏  举报