0

I want to update a table depending on a variable eg:

$number = 3;

UPDATE Table1 m
    SET m.col1 = 1
     WHERE m.id IN (SELECT id From Table2 where other_id = m.other_id) 
ELSE 
     SET all remaining to 0
UPDATE Table1 m SET m.col1 = 0

So all I want is if $number is 0 all records will be 0 if $number > 0 then that quantity of rows needs to be set 1 in Table1 Note: records need to be last records DESC id limit $number

Edit: To better communities what my need is, this how I would successfully accomplish it with php and sql but I will need to run 2 separate queries.

See pic

As you see I'm using two separate queries I was wondering if it could be done with sql only. enter image description here

wilson382
  • 69
  • 7

1 Answers1

0

You can do it with a correlated subquery:

update Table1 m
  set m.col1 = case
    when exists(select 1 from Table2 where other_id  = m.other_id)
      then '1'
      else '0'
    end

I'm not sure if the table aliasing Table1 m works with MySQL. I know that it doesn't work with SQL server. So you might need to write it this way:

update Table1
  set col1 = case
    when exists(select 1 from Table2 m2 where m2.other_id  = Table1.other_id)
      then '1'
      else '0'
    end

The trick is that you use a case when ... then ... else ... end construct. The correlated subquery is within the when ... part. It checks if a related row exists in Table2.

You might want to try the update-with-join trick too, because that's faster. Unfortunately, I cannot try that with my SQL server because that has different syntax. It would look something like this:

UPDATE Table1 m
LEFT JOIN Table2 m2 on (m.other_id = m2.other_id)
SET m.col1 = CASE WHEN m2.other_id IS NULL THEN 0 ELSE 1 END
Community
  • 1
  • 1
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49