php - 插入新行时避免数据库重复

标签 php mysql

您好,我有一个使用以下命令创建的连接表:

CREATE TABLE user_group_join (

    user_group_join_id int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
    user_join_id int(11) NOT NULL,
    group_join_id int(11) NOT NULL,
    FOREIGN KEY (user_join_id) REFERENCES users (user_id),
    FOREIGN KEY (group_join_id) REFERENCES user_group (group_id)

);

然后我还有另一张 table :

CREATE TABLE user_flat(

    user_flat_id int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
    user_flat_user_id INT(11) NOT NULL,
    user_flat_group_id INT(11) NOT NULL,
    user_flat_location varchar(250) NOT NULL,

    FOREIGN KEY (user_flat_user_id) REFERENCES users (user_id),
    FOREIGN KEY (user_flat_group_id) REFERENCES user_group (group_id)

);

user_join_group 用于管理用户权限,现在每次我为特定用户更新单位时,我还需要使用一些唯一值更新 user_group_join 表,例如,如果我有以下值:

user_join_id | group_join_id
          75 | 12
          75 | 13
          75 | 14

如果我想将值 12 从 group_join_id 更改为 13 我应该只:

   user_join_id | group_join_id
              75 | 13
              75 | 14

我尝试删除该行,然后插入新行,但问题如下:

如果我的 ID 为 75 的用户在组 13 中有两套公寓,在组 14 中有一套公寓,如果我用值 12 的组更改两个相似公寓之一,数据库值将是:

user_join_id | group_join_id
          75 | 12
          75 | 14

当我真的想把它拿回来时:

user_join_id | group_join_id
          75 | 12
          75 | 13
          75 | 14

我希望不会令人困惑,有人可以帮助我。非常感谢

最佳答案

我不确定我是否理解正确,所以如果我不理解,请纠正我。

如果一个用户可以拥有多个相同 id 的单位,您应该按如下方式设计数据库:

user_join_id | group_join_id | count
          75 | 12            | 1
          75 | 13            | 2
          75 | 14            | 1

然后,在查询中,您只需减少计数变量,或者如果减少到 0,则删除该行。

关于php - 插入新行时避免数据库重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372061/

相关文章:

php - Laravel Eloquent (PDO) : Check that Transaction is Active

php - 以 sha512 :1000: contain? 开头的 MYSQL 条目是什么

用于 MYSQL 中 NOT IN 查询的 PHP PDO

Python MySQLDB SSL 连接

phpExcel从单元格中读取长数字

php - 使用 Laravel 框架托管 Unity WebGL 游戏

php - 在特定事件发生前 24 小时安排电子邮件通知?

php - 如何根据另一个表 ID 更新一个表 codeigniter

单个查询中的 MySQL 加权平均值

MySQL 外连接 : why does selecting records in ON gives different results than selecting in WHERE?