SQL Server에서 INNER JOIN을 사용하여 여러 테이블에서 삭제하는 방법
MySQL에서는 구문을 사용할 수 있습니다.
DELETE t1,t2
FROM table1 AS t1
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...
SQL Server에서 동일한 작업을 수행하려면 어떻게합니까?
이 예에서 "삭제 된"의사 테이블을 활용할 수 있습니다. 다음과 같은 것 :
begin transaction;
declare @deletedIds table ( id int );
delete from t1
output deleted.id into @deletedIds
from table1 as t1
inner join table2 as t2
on t2.id = t1.id
inner join table3 as t3
on t3.id = t2.id;
delete from t2
from table2 as t2
inner join @deletedIds as d
on d.id = t2.id;
delete from t3
from table3 as t3 ...
commit transaction;
분명히 '출력 삭제'를 할 수 있습니다. 세 번째 테이블에 대한 조인이 필요한 경우 두 번째 삭제에서도 마찬가지입니다.
참고로 insert 문에 insert. *를 수행하고 update 문에 insert. * 및 deleted. *를 둘 다 수행 할 수도 있습니다.
편집 : 또한 table2 + 3에서 삭제하기 위해 table1에 트리거를 추가하는 것을 고려 했습니까? 당신은 암시 적 트랜잭션 내부에있을 것이고 "inserted. "와 "deleted. "가상 테이블도 사용할 수있을 것입니다.
항상 테이블 관계에 계단식 삭제를 설정할 수 있습니다.
하나의 저장 프로 시저에서 여러 삭제를 캡슐화 할 수 있습니다.
트랜잭션을 사용하여 하나의 작업 단위를 보장 할 수 있습니다.
SQL Server의 DELETE에서 FROM 절에 JOIN 구문을 사용할 수 있지만 여전히 첫 번째 테이블에서만 삭제하고 하위 쿼리를 대체하는 독점 Transact-SQL 확장입니다.
-- Transact-SQL extension
DELETE
FROM Sales.SalesPersonQuotaHistory
FROM Sales.SalesPersonQuotaHistory AS spqh INNER JOIN
Sales.SalesPerson AS sp ON spqh.BusinessEntityID = sp.BusinessEntityID
WHERE sp.SalesYTD > 2500000.00;
마스터 테이블에서 일부 레코드를 삭제하고 두 세부 테이블에서 해당 레코드를 삭제하는 예 :
BEGIN TRAN
-- create temporary table for deleted IDs
CREATE TABLE #DeleteIds (
Id INT NOT NULL PRIMARY KEY
)
-- save IDs of master table records (you want to delete) to temporary table
INSERT INTO #DeleteIds(Id)
SELECT DISTINCT mt.MasterTableId
FROM MasterTable mt
INNER JOIN ...
WHERE ...
-- delete from first detail table using join syntax
DELETE d
FROM DetailTable_1 D
INNER JOIN #DeleteIds X
ON D.MasterTableId = X.Id
-- delete from second detail table using IN clause
DELETE FROM DetailTable_2
WHERE MasterTableId IN (
SELECT X.Id
FROM #DeleteIds X
)
-- and finally delete from master table
DELETE d
FROM MasterTable D
INNER JOIN #DeleteIds X
ON D.MasterTableId = X.Id
-- do not forget to drop the temp table
DROP TABLE #DeleteIds
COMMIT
그냥 궁금해 .. 정말 MySQL에서 가능합니까? t1과 t2를 삭제합니까? 아니면 그냥 질문을 오해했습니다.
그러나 여러 조인 조건으로 table1을 삭제하려면 삭제하려는 테이블의 별칭을 지정하지 마십시오.
이:
DELETE t1,t2
FROM table1 AS t1
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...
MSSQL에서 작동하려면 다음과 같이 작성해야합니다.
DELETE table1
FROM table1
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...
다른 두 개의 일반적인 RDBMS가 삭제 작업을 수행하는 방법을 대조합니다.
http://mssql-to-postgresql.blogspot.com/2007/12/deleting-duplicates-in-postgresql-ms.html
Basically, no you have to make three delete statements in a transaction, children first and then parents. Setting up cascading deletes is a good idea if this is not a one-off thing and its existence won't conflict with any existing trigger setup.
In SQL server there is no way to delete multiple tables using join. So you have to delete from child first before delete form parent.
This is an alternative way of deleting records without leaving orphans.
Declare @user Table(keyValue int , someString varchar(10)) insert into @user values(1,'1 value') insert into @user values(2,'2 value') insert into @user values(3,'3 value') Declare @password Table( keyValue int , details varchar(10)) insert into @password values(1,'1 Password') insert into @password values(2,'2 Password') insert into @password values(3,'3 Password') --before deletion select * from @password a inner join @user b on a.keyvalue = b.keyvalue select * into #deletedID from @user where keyvalue=1 -- this works like the output example delete @user where keyvalue =1 delete @password where keyvalue in (select keyvalue from #deletedid) --After deletion-- select * from @password a inner join @user b on a.keyvalue = b.keyvalue
All has been pointed out. Just use either DELETE ON CASCADE
on the parent table
or delete from the child-table
to the parent
.
As Aaron has already pointed out, you can set delete behaviour to CASCADE and that will delete children records when a parent record is deleted. Unless you want some sort of other magic to happen (in which case points 2, 3 of Aaron's reply would be useful), I don't see why would you need to delete with inner joins.
To build upon John Gibb's answer, for deleting a set of data in two tables with a FK relationship:
--*** To delete from tblMain which JOINs to (has a FK of) tblReferredTo's PK
-- i.e. ON tblMain.Refer_FK = tblReferredTo.ID
--*** !!! If you're CERTAIN that no other rows anywhere also refer to the
-- specific rows in tblReferredTo !!!
BEGIN TRAN;
--*** Keep the ID's from tblReferredTo when we DELETE from tblMain
DECLARE @tblDeletedRefs TABLE ( ID INT );
--*** DELETE from the referring table first
DELETE FROM tblMain
OUTPUT DELETED.Refer_FK INTO @tblDeletedRefs -- doesn't matter that this isn't DISTINCT, the following DELETE still works.
WHERE ..... -- be careful if filtering, what if other rows
-- in tblMain (or elsewhere) also point to the tblReferredTo rows?
--*** Now we can remove the referred to rows, even though tblMain no longer refers to them.
DELETE tblReferredTo
FROM tblReferredTo INNER JOIN @tblDeletedRefs Removed
ON tblReferredTo.ID = Removed.ID;
COMMIT TRAN;
DELETE TABLE1 LIN
FROM TABLE1 LIN
INNER JOIN TABLE2 LCS ON CONDITION
WHERE CONDITION
$sql="DELETE FROM basic_tbl
,education_tbl
, personal_tbl
,address_tbl
,department_tbl
USING basic_tbl
,education_tbl
, personal_tbl
,address_tbl
,department_tbl
WHERE b_id
=e_id
=p_id
=a_id
=d_id
='".$id."' "; $rs=mysqli_query($con,$sql);
'Programing' 카테고리의 다른 글
PHP 네임 스페이스 및 "사용" (0) | 2020.08.10 |
---|---|
.NET MemoryCache의 적절한 사용을위한 잠금 패턴 (0) | 2020.08.10 |
디자인 패턴과 건축 패턴의 차이점은 무엇입니까? (0) | 2020.08.10 |
Python Pandas : 행별로 데이터 프레임 채우기 (0) | 2020.08.10 |
모의 객체 초기화-MockIto (0) | 2020.08.10 |