我正在尝试修复一个不完整的数据库,我无法控制架构,我需要找到丢失的条目并插入它们。
这是我到达的语法:
INSERT INTO
downloads (product_id, filename)
VALUES
(
products_id = ( SELECT id
FROM products
WHERE id NOT IN
( SELECT product_id
FROM downloads
)
),
filename = 'default.zip'
)
子查询单独工作正常,但上面引发错误
#1093 - You can't specify target table 'download' for update in FROM clause
我已经回顾了许多与此错误相关的StackOverflow问题(like this),并且我认为有一种方法可以嵌套子查询,使其“creates an implicit temporary table, so it doesn't count as the same table you're updating”但我没有'能够适应它。
如果我的方法效率低下没关系,我很好奇看到一个与我的语法接近的解决方案,但任何解决方案都会有所帮助。
答案 0 :(得分:2)
要做的事,
INSERT...INTO SELECT
声明LEFT JOIN
代替NOT IN
products.ID
和downloads.product_id
以提高性能查询,
INSERT INTO downloads (product_id, filename)
SELECT a.id AS product_id, 'default.zip' AS filename
FROM products a
LEFT JOIN downloads b
ON a.ID = b.product_id
WHERE b.product_id IS NULL