mysql - 如果 MySQL 表中不存在,则添加一行

标签 mysql

在一个表中有 2 列:useridroleid。每个用户至少应该有 roleid 4 。目前大约有 10.000 条记录,但不知为何有一小部分用户没有此角色。

视觉示例:

userid  |  roleid
1          1
1          4
2          1
2          4
3          1 <---------- userid 3 misses roleid 4!
4          1
4          4

当该组合不存在时,是否可以执行查询并添加包含 userid 和 roleid 的行?

最佳答案

是的。

insert into userRoles(userid, roleid)
    select userid, 4
    from userRoles
    group by userid
    having sum(roleid = 4) = 0;

having 子句中的sum(role = 4) 计算具有4 的每个用户的行数。 = 0 表示没有。

注意:这为该表中的所有用户提供了 4 的角色 ID。可能有些用户根本没有角色。

如果您需要它们,请使用 users 表:

insert into userRoles(userid, roleid)
    select u.userid, 4
    from users u
    where not exists (select 1 from userRoles ur where ur.userid = u.userid);

关于mysql - 如果 MySQL 表中不存在,则添加一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42137263/

相关文章:

php - 代码点火器 undefined variable 结果问题

php - 时段预订脚本 - 检查可用性

mysql - mysql 5.7 中的分组依据

php - mysql 连接两个表

php - 来自mysql的多维数组用于数据可视化

MySQL按查询进行分组,不使用索引,滞后于使用文件排序

php - 如何从 Laravel belongsToMany 关系中获取行?

PHP 和 MySQL 将所有日期行更新为时间戳

php - 数据库中的 DATETIME 问题

python - 在 Python 中使用占位符时出现 MySQL 语法错误