如何在where子句中使用子查询更新表

时间:2011-12-08 13:52:09

标签: mysql subquery sql-update

我有一个像这样的主表categories

categories_id | categories_status | parent_id
     1                  1               0
     2                  1               0
     3                  1               1
     4                  1               2
     5                  1               1
     6                  1               2

和参考表products_to_categories

categories_id | products_id
      3             778
      3             998
      5             666
      5             744

我选择所有没有子类别的类别:

SELECT * FROM categories
WHERE categories_id not in ( SELECT parent_id FROM categories )
# gets entries with id 3, 4, 5, 6

并且参考表中没有产品:

AND categories_id NOT IN ( SELECT categories_id FROM products_to_categories )
# gets entries with id 4, 6

现在我想为这个结果更新categories_status,但它只是将SELECT更改为UPDATE:

UPDATE categories
SET categories_status = 0
WHERE categories_id not in ( SELECT parent_id FROM categories )
AND categories_id NOT IN ( SELECT categories_id FROM products_to_categories )

有一些类似的问题,但我无法弄清楚如何改变我的榜样......

谢谢&最好的问候,

亚历

3 个答案:

答案 0 :(得分:2)

您无法更新子查询中包含条件的记录。 尝试使用直接条件,如:

// this rely that all categories_id higher than 0 should be valid relations
WHERE categories_id < 1

..这应该可行,但我想给你关于性能的建议 - 如果没有父项的记录,请使用NULL值。 条件应该是WHERE categories_id IS NULL

答案 1 :(得分:2)

使用左外连接

而不是子查询
update 
categories c1
left outer join categories c2 on c1.ID = c2.Parent_id
left outer join products_to_categories p on c1.categories_id = p.categories_id
set c1.categories_status = 0
where c2.ID is null and p.categories_id is null

答案 2 :(得分:0)

我有一个更新问题:

 UPDATE [base].[dbo].[test] SET Idstatement = 20    
 WHERE Iddoc IN 
             (SELECT [Iddoc] FROM [base].[dbo].[test] 
              WHERE Document = 'INV' AND Idstatement = 50 AND Year = '2017'
             )

子查询返回了多个值。

当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。 该声明已终止。