2011-11-28 5 views
7

여기에 두 개의 테이블이 있습니다다른 테이블의 값을 기반으로 한 테이블의 레코드를 삭제하는 방법은 무엇입니까?

cm_id cost 
1  6.52 
2  16.52 
3  2.12 
4  7.14 
5  19.09 
6  11.52 
7  0.12 

표 2

um_id order_num name 
1  517   tommy 
2  518   bobby 
3  519   scotty 
4  520   faris 
5  521   justine 
6  522   sadie 
7  523   nicole 

cm_id 및 비용을 각 주문 번호에 연결 할 수 있도록 즉,

SELECT table1.cm_id, table1.cost, table2.order_num, table2.order_num 
FROM table1, table2 
WHERE table1.cm_id=table2.um_id; 
을 같은 일을 대표 um_id

행을 삭제하는 데 사용할 수있는 단일 SQL 문은 무엇입니까? table2에서 order_num이 518과 520 사이에있는 table1에서?

+2

내가이 [귀하의 질문에 대답]한다고 생각이 방법 (http://stackoverflow.com/questions/439750/t-sql-selecting-rows-to-delete-via-를 선호 조인). 조인을 사용하십시오. – Ryan

+0

참고로, 나는 많은 것을 배웠다. – user784637

+0

중복 된 http://stackoverflow.com/questions/1590799/delete-all-rows-in-a-table-based-on-another-table – Igor

답변

15
delete 
from table1 
where cm_id IN (select um_id from table2 where order_num between 518 and 520) 
+4

많은 양의 데이터에 효율적이지 않음 –

+0

왜 안 되니? 효율적인 무엇입니까? 다른 방법이 있습니까? – bornfromanegg

1

사용 하위 쿼리와 함께 삭제 :

DELETE * FROM table1 WHERE table1.cm_id IN (SELECT table2.um_id FROM table2 WHERE order_num>=518 and order_num<=520) 
+0

DELETE FROM DELETE * FROM – Cristiana214

7
DELETE table1 
FROM table1 INNER JOIN table2 ON table1.cm_id = table2.um_id 
AND (table2.order_num BETWEEN 518 AND 520) 

--OR 

DELETE 
FROM table1 
USING table1 INNER JOIN table2 ON table1.cm_id = table2.um_id 
WHERE (table2.order_num BETWEEN 518 AND 520) 

편집 :이 중복 FROM이고 쿼리가 Andriy M 의견에 따라 변경되었습니다

.

+0

이것은 SQL Server에서 작동합니다. [MySQL에서] (http://dev.mysql.com/doc/refman/5.0/en/delete.html "MySQL :: MySQL 5.0 참조 설명서 :: 12.2.2 DELETE 구문") 당신은 * a) * 첫 번째 'FROM'또는 * b) *를 제거하고 두 번째 'FROM'을 'USING'으로 바꿉니다. –

+0

또한이 두 쿼리가 서로 어떻게 다른가요? (제 말은 두 번째 것에 더 적은 공백이 있다는 사실을 제외하고) –

+0

오, 사실 WHERE 절을 두 번째 쿼리에 넣는 것을 잊었습니다. 그에 따라 달라집니다. 감사합니다. –

3

나는

delete from table1 
using table1, table2 
where table1.cm_id = table2.um_id 
and table2.order_num >= 518 
and table2.order_num <= 520; 
관련 문제