Skip to content
Advertisement

SQL Update Table 1 when Table 2 contains a specific value

I want to update lasstock of table s_articles to 1 when laststock is 0 and is either in categoryID 242, 243 or 244 in table s_articles_categories_ro.

I came up with this SQL, which doesn’t work.

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)

I have these 2 tables:
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

Advertisement

Answer

You should be able to use exists correlated query here

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
   );
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement