我有两张桌子:产品(product_id,日期)和性别(product_id,sex)。
我想从products表中删除所有具有product_id的产品,其中product_id在性别表中存在一行,其product_id和sex = 1。
我还希望从性表中删除包含我将从products表中删除的一行中包含的product_id的所有行。 (这可能会删除每个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;
执行前
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语句给了我一个语法错误。我注意到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;
答案 0 :(得分:1)
我认为您正在寻找CREATE TEMPORARY TABLE
来创建表而不是DECLARE
。
有关在MySQL中创建表的更多信息,请参阅this page。
您使用的语法似乎是针对MS SQL服务器,而不是MySQL。在MySQL中,DECLARE
用于局部变量,条件,处理程序和游标,但不用于创建表。
答案 1 :(得分:1)
试试这个吗?
CREATE TEMPORARY TABLE tempTable
SELECT product_id
FROM products AS p
INNER JOIN sex AS s
ON p.product_id = s.product_id
WHERE s.sex = 1;
DELETE FROM products AS p
NATURAL JOIN tempTable AS t
WHERE p.product_id = t.product_id;
是的,你不能DELETE FROM same_table (SELECT * FROM same_table)
。
我引用:
Currently, you cannot delete from a table and select from the same table in a subquery.
答案 2 :(得分:1)
我认为你可以通过一个简单的多重删除获得你想要的东西:
delete sex, products from products p
inner join sex s on p.id=s.product_id
where s.sex=1
您还可以考虑在桌面上使用on cascade delete
:
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html