我有一个表,我想在其中为每个用户存储多一个键,下面是该表,
我试图为每个现有用户添加app_reminder
。 我这样做是因为
insert into users_settings (user_id, key)
select distinct user_id, 'app_reminder'
from users_settings;
现在我要添加where子句
选择DISTINCT user_id,'app_rements',其中键!='app_rements'
用于防止重复输入。 我试过以上一个,但它没有工作。
如果有人能给我指点一下,我将不胜感激。
谢谢
一种方法简单地使用条件聚合:
insert into users_settings (user_id, key)
select user_id, 'app_reminder'
from users_settings
group by user_id
having sum(key = 'app_reminder') = 0;
您可能需要一个更通用的解决方案。 如果要确保用户/键对永远不会重复,请在这些列上创建唯一约束或索引:
alter table users_settings add constraint unq_users_settings_user_id_key
unique (user_id, key);
然后,可以使用On duplicate key Update
跳过插入行:
insert into users_settings (user_id, key)
select distinct user_id, 'app_reminder'
from users_settings
on duplicate key update user_id = values(user_id);
更新
不执行任何操作,因为值是相同的。 MySQL跳过插入操作,并且不返回错误。