SQL 当 Table 2 包含特定值时更新 Table 1

SQL Update Table 1 when Table 2 contains a specific value

我想在 laststock 时将 table s_articleslasstock 更新为 1 为 0,并且在 categoryID 242、243 或 244 中 table s_articles_categories_ro

我想出了这个 SQL,但行不通。

UPDATE a
SET a.laststock = 1
FROM s_articles AS a
LEFT JOIN `s_articles_categories_ro` AS ac
ON a.id = ac.articleID
WHERE a.laststock=0 AND ac.categoryID IN (242,243,244)

我有这 2 个 table:
s_articles

id laststock
1 0
2 1
3 0
4 0

s_articles_categories_ro

id articleID categoryID
1 1 242
2 1 12
3 1 8
4 2 2
5 3 8
6 4 21
7 1 244

UPDATE 语句可能需要在 MySQL 中的 SET 之前使用 JOIN,我认为我们可能会使用 JOIN 而不是 OUTER JOIN

UPDATE s_articles a
INNER JOIN `s_articles_categories_ro` AS ac
ON a.id = ac.articleID
SET a.laststock = 1
WHERE a.laststock = 0 AND ac.categoryID IN (242,243,244)

您应该可以在此处使用 exists 相关查询

update s_articles a
set laststock = 1
where laststock = 0
 and exists (
   select * from s_articles_categories_ro ac 
     where ec.categoryId in (242,243,244) 
       and ac.articleId = a.Id
   );

为什么使用“左连接”?

试试这个:

UPDATE s_articles
JOIN  s_articles_categories_ro ON s_articles.id = s_articles_categories_ro.articleID 
SET laststock = 1
WHERE s_articles.laststock=0 AND s_articles.categoryID IN (242,243,244)

另一种选择

试试这个:

UPDATE s_articles SET laststock = 1
Where id in (
SELECT id from s_articles
JOIN  s_articles_categories_ro ON s_articles.id = s_articles_categories_ro.articleID 
WHERE s_articles.laststock=0 AND s_articles.categoryID IN (242,243,244)
)