1

I have a table 'users' with the columns:

user_id(PK), user_firstname, user_lastname

and another table 'room' with the columns:

event_id(PK), user_id(FK), user_firstname, user_lastname....(and more columns).

I want to know if it is possible to fill the user_firstname and user_lastname automatically just knowing the user_id column.

Like the default value of user_firstname would be like: "select users.user_firstname where users.user_id = user_id"

I don't know if was clear enough...As you can see my knowledge in database is very narrow.

4

3 回答 3

4

列 user_firstname 和 user_lastname 不属于您的房间表。user_id 列引用了 users 表,这就是您所需要的。要选择数据,您可以使用 JOIN 语句,例如

SELECT R.event_id, R.user_id, U.user_firstname, U.user_lastname
FROM room AS R
JOIN users AS U ON R.user_uid = U.user_id
于 2013-08-21T21:34:20.553 回答
4

你想达到的目标可以用JOINs 来完成。他们将避免那些多余user_firstnameuser_lastname列。因此,您只需在查询房间表时从两个表中获取数据,然后将额外的列users添加到结果集中:

SELECT * FROM room AS r INNER JOIN users AS u ON r.user_id = u.user_id;

我们在这里所做的事情称为规范化。在您的情况下,要注意的另一件重要事情是外键约束及其级联room.user_id references user.user_id。如果你想删除用户,一个deleteonuser应该很可能级联到,而不是标记他们已删除。room

于 2013-08-21T21:34:30.053 回答
2

这里的答案是问题的侧面。您希望在 Event 表中有一个user_firstnameanduser_lastname列。user_id是整个 User 表中该行的代理。当您需要访问user_firstname时,您对公共列上的两个表进行JOIN 。

于 2013-08-21T21:36:11.253 回答