【问题标题】:How to update a value within a column with another value- Oracle如何用另一个值更新列中的值-Oracle
【发布时间】:2021-09-22 21:10:58
【问题描述】:

我有一个静态表,我想用一个字符串替换一个特定的值。换句话说,在我的表中,我想将 type_1 列中的值 dog 替换为 'primate'。

这是我的桌子:

t_id|type_1|count
1, dog, 22
2, cat, 55
3, bird, 12

这是我的预期输出:

t_id|type_1|count
1, primate, 22
2, cat, 55
3, bird, 12

如你所见,我只是想把价值狗换成价值灵长类动物。

到目前为止,这是我的代码:

SELECT REPLACE(t.type_1, 'dog', 'primate')
  FROM table_1 t
  where t.type_1 = 'dog' and t.t_id='1'

我是 oracle sql 的新手,所以语法对我来说有点混乱。任何想法或建议都会有所帮助。

【问题讨论】:

    标签: sql oracle oracle11g sql-update


    【解决方案1】:

    如果您只想查询,请使用case 表达式:

    select t.t_id,
           (case when t.type_1 = 'dog' then 'primate' else t.type_1 end) as type_1,
           t.count
    from table_1 t;
    

    如果您想更改表中的值(即永久),请使用update

    update table_1
        set type_1 = 'primate'
        where type_1 = 'dog';
    

    【讨论】:

      【解决方案2】:

      好像更新了。

      这就是你所拥有的:

      SQL> select * from animal;
      
            T_ID TYPE_1            CNT
      ---------- ---------- ----------
               1 dog                22
               2 cat                55
               3 bird               12
      

      把“狗”改成“灵长类”:

      SQL> update animal set type_1 = 'primate' where type_1 = 'dog';
      
      1 row updated.
      

      结果:

      SQL> select * from animal;
      
            T_ID TYPE_1            CNT
      ---------- ---------- ----------
               1 primate            22
               2 cat                55
               3 bird               12
      
      SQL>
      

      或者,如果您只需要 select 语句,那么 case 可能会这样做:

      SQL> select t_id,
        2         case when type_1 = 'dog' then 'primate'
        3              else type_1
        4         end as type,
        5         cnt
        6  from animal;
      
            T_ID TYPE              CNT
      ---------- ---------- ----------
               1 primate            22
               2 cat                55
               3 bird               12
      
      SQL>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-13
        • 1970-01-01
        • 1970-01-01
        • 2019-08-20
        • 1970-01-01
        • 1970-01-01
        • 2014-01-17
        • 1970-01-01
        相关资源
        最近更新 更多