简体   繁体   English

SQL条件更新案例

[英]SQL conditional update case

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 所以我想要的是,如果$ number为0,那么如果$ number> 0,那么所有记录将为0,那么该行的数量需要在表1中设置为1。注意:记录必须是最后一条记录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. 编辑:为了更好的社区我需要什么,这就是我将如何使用php和sql成功完成它,但是我将需要运行2个单独的查询。

See pic 见图片

As you see I'm using two separate queries I was wondering if it could be done with sql only. 如您所见,我正在使用两个单独的查询,我想知道是否可以仅使用sql来完成。 在此处输入图片说明

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. 我不确定表别名Table1 m适用于MySQL。 I know that it doesn't work with SQL server. 我知道它不适用于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. 诀窍是您case when ... then ... else ... end构造case when ... then ... else ... end使用了一种case when ... then ... else ... end The correlated subquery is within the when ... part. 相关的子查询在when ...部分内。 It checks if a related row exists in Table2 . 它检查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. 不幸的是,我无法在SQL Server上尝试这种方式,因为它具有不同的语法。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM