DELETE FROM table_a WHERE id IN(
SELECT table_a.id AS id FROM table_a, table_b
WHERE table_a.object_id = 1 AND table_a.code = 'code'
AND table_a.code = table_b.code
AND table_b.id = table_a.b_id
AND table_b.table = 'testTable')
这是我希望MySQL执行的(稍微简化)查询。我在stackoverflow的其他页面上读到这是不受支持的,并且它可以通过使用JOINS来解决。如何使用JOINS将其“转录”为查询?我发现很难这样做,因为我从未尝试过使用多个表创建DELETE查询。
答案 0 :(得分:5)
您不能从表中删除并引用子查询中的同一个表 - 只是MySQL的限制。以下内容应该有效:
DELETE FROM table_a
USING table_a
INNER JOIN table_b
ON table_a.code = table_b.code
AND table_b.id = table_a.b_id
AND table_b.table = 'testTable'
WHERE table_a.object_id = 1
AND table_a.code = 'code'
重要的部分是USING
。如果您只是加入这两个表,您将从两个表中删除记录。 USING
告诉MySQL使用这些表进行处理,但只删除FROM
子句中的表。
答案 1 :(得分:4)
这是一个常见的MySQL问题,在select和update / delete之间使用临时表:
DELETE FROM table_a WHERE id IN
(select id from
(SELECT table_a.id AS id FROM table_a, table_b
WHERE table_a.object_id = 1
AND table_a.code = 'code'
AND table_a.code = table_b.code
AND table_b.id = table_a.b_id
AND table_b.table = 'testTable')
) tempTable
答案 2 :(得分:2)
有两种(略有不同的)语法可以从多个表中删除。这是没有USING
的那个:
DELETE a
FROM
table_a AS a
INNER JOIN
table_b AS b
ON b.code = a.code
AND b.id = a.b_id
WHERE
a.object_id = 1
AND a.code = 'code'
AND b.`table` = 'testTable' --- Do you actually have a column named "table"?
答案 3 :(得分:0)
我的方式......如果你可以使用它!
DELETE FROM table_a WHERE id IN(SELECT id FROM(SELECT id FROM table_a WHERE userid=99 GROUP BY mobile HAVING COUNT(mobile) > 1) as t2)