【问题标题】:Is it possible to add data in a field that already has existing data stored?是否可以在已存储现有数据的字段中添加数据?
【发布时间】:2016-12-14 13:03:03
【问题描述】:

与更新整个字段相比,是否可以在字段中添加数据?

例如,在表格中

ID FName Interests 
1  Geno  Math

我是否可以编写一条 SQL 语句,而不是更新 id = 的兴趣并重新输入数学、科学。相反,我可以只插入值 Science 并将其插入到当前存储的数据之后的兴趣字段中?

ID FName   Interests
1   Geno   Math, Science

【问题讨论】:

    标签: mysql sql database insert alter


    【解决方案1】:

    你可以试试这个:

    Update [YourTable]
    SET Interests= CONCAT(Interests,',Science')
    WHERE Id=[someid]
    

    您可以使用CONCAT() 更新,science 与现有列值。

    【讨论】:

      【解决方案2】:

      有可能,但不要这样做!您的数据库中有两个不同的实体,“用户”(某种)和“兴趣”。

      存储这些数据的正确方法是使用每个用户和兴趣一行一行的表:

      create table UserInterests (
          UserInterestId int auto_increment primary key,
          UserId int not null,
          Interest varchar(255),
          constraint fk_UserInterests_UserId foreign key (UserId) references ?(id)
      );
      

      然后你可以很容易地分配一个新的兴趣:

      insert into UserInterests
          values ($userId, $interest);
      

      (注意:您应该对此类查询使用参数,而不仅仅是将值放入查询字符串中。)

      为什么这是“正确”的方式?考虑以下几点:

      • SQL 列(JSON 和 XML 等特殊类型除外)旨在存储单个值。
      • SQL 具有用于存储列表的出色数据结构;它被称为
      • MySQL 没有特别强大的字符串函数。
      • 兴趣查询不能利用兴趣。
      • 简单的事情,比如获取兴趣列表,对于将值组合成一个字符串真的非常困难。

      【讨论】:

        【解决方案3】:

        您可以使用如下CONCAT() 函数,但最后您必须执行UPDATE 操作。

        update tbl1
        set Interests = concat(Interests,', Science')
        where id =1;
        

        【讨论】:

          【解决方案4】:

          你不需要重新输入,只需连接 -

          update t  
          set col=concat_ws(',',col,'new att')  
          where ...
          

          但你并不想这样做。
          糟糕的设计。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-05-04
            • 2018-02-17
            • 2018-10-17
            • 1970-01-01
            • 2012-09-10
            • 2013-10-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多