如果主键在同一个表中用作外键,如何添加数据?

时间:2022-11-02 10:23:28

I am implementing a referral system in which a user can come form a reference of a previously registered user of my system or can register manually without any reference. The problem I am facing is that if the user is not using a reference token to register then the referee of the user is that user itself. How can I save the data (foreign key) of the user before getting the primary key of that row (that comes from auto increment method)? For more clearance I am attaching this image.如果主键在同一个表中用作外键,如何添加数据?

我正在实现一个推荐系统,在这个系统中,用户可以来自我的系统的一个以前注册的用户的引用,或者可以手工注册,而不需要任何引用。我所面临的问题是,如果用户没有使用引用令牌来注册,那么用户的裁判就是那个用户本身。如何在获取该行的主键(来自自动递增方法)之前保存用户的数据(外键)?为了获得更多的清除,我附上这张图片。

Thanks in advance.

提前谢谢。

1 个解决方案

#1


2  

One way to go is to auto generate the key before inserting instead of using the auto increment feature. The easiest way of doing this would be to define the ID columns as uuids instead of ints and generate the next id from your application.

一种方法是在插入之前自动生成键,而不是使用自动增量特性。最简单的方法是将ID列定义为uuid,而不是ints,并从应用程序生成下一个ID。

A better, though, IMHO, is to change your design, and instead of using the user as his own referral in case he wasn't referred by another user just explicitly state he has no referral and use a null value there.

更好的方法,IMHO,是改变你的设计,而不是使用用户作为他自己的引用,以防其他用户没有引用他,只是明确地声明他没有引用,并使用一个空值。

#1


2  

One way to go is to auto generate the key before inserting instead of using the auto increment feature. The easiest way of doing this would be to define the ID columns as uuids instead of ints and generate the next id from your application.

一种方法是在插入之前自动生成键,而不是使用自动增量特性。最简单的方法是将ID列定义为uuid,而不是ints,并从应用程序生成下一个ID。

A better, though, IMHO, is to change your design, and instead of using the user as his own referral in case he wasn't referred by another user just explicitly state he has no referral and use a null value there.

更好的方法,IMHO,是改变你的设计,而不是使用用户作为他自己的引用,以防其他用户没有引用他,只是明确地声明他没有引用,并使用一个空值。