我试图找出更新表格中两个字段之一的最佳方法。我有一个人关系表,它链接两个人,我希望每个人都能够在他们的最后设置关系类型。
PersonRelationship Table
id int
user1_id int
user2_id int
user1_reltype /* boss, manager, etc */
user2_reltype
根据当前用户是表中的user1_id还是user2_id,我需要相应地更新user_reltype。所以基本上如果当前的userid在user1_id字段中,那么更新user1_reltype,否则更新user2_reltype。
答案 0 :(得分:0)
由于您希望每个用户能够独立管理他们的一半关系,因此您可以简化表格结构
--------------------------------------
| initiator_id | reltype | target_id |
当身份证号为5的人(“发起人”)将身份证号为9的人(“目标人”)标记为朋友时,该表格将包含:
---------------------------------------
| initiator_id | reltype | target_id |
+--------------+----------+-----------+
| 5 | 'friend' | 9 |
如果第9个人后来发起与人5的“老板”连接,则可以创建该条目而不会干扰之前由人5创建的行:
--------------------------------------
| initiator_id | reltype | target_id |
+--------------+---------+_----------+
| 9 | 'boss' | 5 |
这种方法可以使您的表格易于阅读,并且您的查询易于编写。
<强>附加强>
如果您还没有,请考虑创建另一个表来跟踪关系类型('reltype'):
-----------------
| id | type |
+----+----------+
| 1 | 'friend' |
| 2 | 'boss' |
并使用外键替换关系表中的字符串reltype。
---------------------------------------
| initiator_id | reltype | target_id |
+--------------+----------+-----------+
| 5 | 1 | 9 |
| 9 | 2 | 5 |