与更新整个字段相比,是否可以在字段中添加数据?是否可以在已存在现有数据的字段中添加数据?
例如,在一个表
ID FName Interests
1 Geno Math
是否有可能为我写的,而不是更新的兴趣其中id =和重新输入数学,科学的SQL语句。相反,我可以插入价值科学,并将其插入兴趣领域后,目前存储的数据?
ID FName Interests
1 Geno Math, Science
与更新整个字段相比,是否可以在字段中添加数据?是否可以在已存在现有数据的字段中添加数据?
例如,在一个表
ID FName Interests
1 Geno Math
是否有可能为我写的,而不是更新的兴趣其中id =和重新输入数学,科学的SQL语句。相反,我可以插入价值科学,并将其插入兴趣领域后,目前存储的数据?
ID FName Interests
1 Geno Math, Science
你可以试试这个:
Update [YourTable]
SET Interests= CONCAT(Interests,',Science')
WHERE Id=[someid]
您可以通过使用CONCAT()
与现有的列值附加,science
更新。
您可以使用CONCAT()
函数,但最后您必须执行UPDATE
操作。
update tbl1
set Interests = concat(Interests,', Science')
where id =1;
你不需要重新输入,只有连击 -
update t
set col=concat_ws(',',col,'new att')
where ...
但你真的不希望这样做。
糟糕的设计。
这是可能的,但不要这样做!数据库中有两个不同的实体,“用户”(某种)和“兴趣”。
来存储这些数据的正确方法是使用一个表,每个用户和兴趣一行:
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);
(注:您应该使用这些查询的参数,而不是将这些值放入查询字符串中。)
为什么这是“正确”的方式?请考虑以下几点: