简体   繁体   English

将user_id从sql中的一个表转换为另一个表

[英]Translating user_id from one table in sql to another table

I have a database with a "session" table, a "log" table and a "users" table(among others). 我有一个数据库,其中包含“会话”表,“日志”表和“用户”表(以及其他)。 The user_id in the "log" and "session" tables is a number. “日志”和“会话”表中的user_id是一个数字。 This number shows up in the users table under user_id(it generates a random number when a new user is created). 此数字显示在user_id下的users表中(创建新用户时会生成一个随机数)。

Each time a user logs in, a row is added to both the "session" and "log" tables with that number as the user_id. 每次用户登录时,都会向该“会话”和“日志”表中添加一行,并以该数字作为user_id。 I'd like to make it so that when a user logs in, his actual username gets written to the database, not the number. 我想这样做,以便用户登录时,其实际用户名被写入数据库,而不是数字。 Somehow I'd like it to look up that user_id number in the "users" table and translate it to the username in the "users" table and write it to the "sessions" and "log" tables. 我以某种方式希望它在“用户”表中查找该user_id号,并将其转换为“用户”表中的用户名,并将其写入“会话”和“日志”表中。

Maybe add some code to my session_util.php file to accomplish this? 也许将一些代码添加到我的session_util.php文件中以完成此操作? I really hope this all makes sense to someone. 我真的希望这对某人有意义。

It would be easier if we could see your schemas, but the queries you are looking for are something like the following: 如果我们可以看到您的架构,则会更容易,但是您要查找的查询如下所示:

To get the username by id: 要通过ID获取用户名:

"SELECT username FROM users WHERE user_id='" + id + "';"

That query should get you the username, which you can assign to a local variable for use in your insert statements. 该查询应该为您提供用户名,您可以将其分配给本地变量以在插入语句中使用。 In your insert statements, change the user_id to username (you will need to alter your schema assuming that user_id is an int and username is a varchar). 在您的插入语句中,将user_id更改为username(您需要更改您的架构,假设user_id是一个int且username是一个varchar)。

I would suggest to you to continue using the user_id for the identifier though, since it is an id it should be guaranteed that it is a unique identifier. 我建议您继续使用user_id作为标识符,因为它是一个id,所以应保证它是唯一的标识符。 You can then use the sql statement above to turn this id into a username and use that where you need it. 然后,您可以使用上面的sql语句将该ID转换为用户名,并在需要时使用该用户名。

Need some more info. 需要更多信息。 First, What are your table attributes (you'll need a user name column in both the log and session tables to start with) and are you using OOP? 首先,您的表属性是什么(首先在日志表和会话表中都需要一个用户名列),并且您正在使用OOP吗?

Why would you want to have the user name instead of the id ? 为什么要使用用户名而不是ID? Why not convert the id to the name when you are outputting the data and keep the id number in the tables? 在输出数据并将ID号保留在表中时,为什么不将ID转换为名称呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM