How to set MYSQL column to certain value if a certain row exists?

后端 未结 1 411
無奈伤痛
無奈伤痛 2021-01-26 13:37

I want to generate a new column in my table that is true if a row exists with certain conditions.

name | col1 | col2 | flag
--------------------------
a      1           


        
相关标签:
1条回答
  • 2021-01-26 14:15

    So you want just to get those values from db? or you want to add column? those are 2 different goals.

    So if you need just to get those values you can:

    http://sqlfiddle.com/#!9/65b4c2/1

    SELECT t.*, t2.flag
    FROM table_name t
    LEFT JOIN (
      SELECT name, MAX(IF(col1=2 AND col2=3,1,0)) flag
      FROM table_name
      GROUP BY name
      ) t2
    ON t.name = t2.name
    

    and if you really need to add new column then you go this way:

    http://sqlfiddle.com/#!9/226fb3/1

    ALTER TABLE table_name ADD COLUMN flag TINYINT;
    
    UPDATE table_name t
    LEFT JOIN (
          SELECT name, MAX(IF(col1=2 AND col2=3,1,0)) flag
          FROM table_name
          GROUP BY name
          ) t2
    ON t.name = t2.name
    SET t.flag=t2.flag
    
    0 讨论(0)
提交回复
热议问题