我有兩個表:product(product_id,date)和sex(product_id,sex)。我該如何解決這個DELETE查詢?
我想從產品表中刪除所有帶有此product_id和sex = 1的性別表中存在行的product_id的產品。
我也希望從性別表中刪除所有包含我從產品表中刪除的行中包含的product_id的行。執行
DELETE FROM products
WHERE product_id IN (SELECT product_id FROM @recordsToDelete);
DELETE FROM sex
WHERE product_id IN (SELECT product_id FROM @recordsToDelete);
但DECLARE語句之前(這可能會刪除每PRODUCT_ID多行。)
到目前爲止,我有
DECLARE @recordsToDelete AS TABLE(
int product_id
);
INSERT INTO @recordsToDelete(product_id)
SELECT product_id
FROM products p
JOIN sex s
ON p.product_id = s.product_id
WHERE s.sex = 1;
我會再與
SELECT * FROM @recordsToDelete;
測試給我一個語法錯誤。我注意到here DECLARE需要一個BEGIN/END複合語句,但我無法正確表述它。我怎樣才能糾正我的錯誤?
編輯:
通過
CREATE TEMPORARY TABLE recordsToDelete(
product_id INT
);# MySQL returned an empty result set (i.e. zero rows).
INSERT INTO recordsToDelete(product_id)
SELECT p.product_id
FROM products p
JOIN sex s ON p.product_id = s.product_id
WHERE s.sex =1;# Affected rows: 275
SELECT *
FROM recordsToDelete;
謝謝,它w現在開始。 – jela 2012-04-17 18:06:02