Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql Update based on existence in other table

Tags:

sql

mysql

I'm trying to figure out how to mass update a mysql table based on if a value exists in a column in another table.

e.g. pseudo code:

if Table1.`col`=Table2.`col` then
  Update Table1.`status`=1

or

if table2.`col` exists in table1.`col`
  Update Table1.`status`=1

What's the best way to achieve this?

like image 345
stackedandflowed Avatar asked Feb 23 '23 09:02

stackedandflowed


2 Answers

Try this one -

UPDATE table1 t1
  JOIN table2 t2
    ON t1.col = t2.col
SET t1.status = 1;
like image 138
Devart Avatar answered Mar 03 '23 16:03

Devart


Table 1

col  | status 
-------------

jaga |   0

kala |   0

Table 2

col   | status 
--------------

jaga  |   1

latha |   0

If Table1.col=Table2.col // So this point is fullfill jaga record. then Update Table1.status=1 // So Table 1 jaga row status want to Update in 1.

Is I am Correct?.

Then Try

UPDATE Table1 AS t1, Table2 AS t2 SET t1.col = 1 WHERE t1.col  = t2.col

Happy Codings,

like image 25
Sagotharan Avatar answered Mar 03 '23 17:03

Sagotharan