8

我正在尝试为 MySQL 设计一个用户表。

现在,我的用户表看起来像这样

users (
BIGINT id,
VARCHAR(?) username,
VARCHAR(?) password,
VARCHAR(254) email,
DATETIME last_login,
DATETIME data_created
)

我还应该包括哪些其他字段,为什么需要它们?

我应该从上面排除哪些字段,为什么?

我应该为用户名和密码分配多少个字符,为什么?

我应该使用 BIGINT 作为 id 吗?

预先感谢您的帮助。

已添加 我将使用该表作为社交网站,因此“用户”是指世界各地的人。

4

3 回答 3

18

A few comments:

  1. BIGINT is fine. I assume you're using it as a surrogate key. In that case, declare it as

    BIGINT id primary key auto_increment,

    Mysql will automatically allocate a unique int value to your id whenever you do an insert (don't specify any value for this field). Never try to implement this behaviour by selecting the max id and adding 1 to it (I've seen this so many times).

  2. Length of username and password: this is no big deal really, just pick a length. I tend to standardise on 255 length varchars for these things but that's not based on anything empirical.

  3. Call your table "user", not "users". Conceptually, a table implements an entity in the same way that a class implements an entity. You will likely create a class or data structure called "user" and the table name should correspond to this.

  4. Every table that I create has two timestamps, "created" and "last_updated". You're halfway there:)

  5. I don't think I would store last_login in the user table, this is likely to be something that you will want to log in a separate table. It's a good idea to store all login events (login, logout, failed attempt, account lock etc.) in a logging table. This will give you much better visibility of what the system has been doing.

于 2011-04-11T13:02:26.650 回答
4

1/ 用户名和密码:自己决定你希望这些有多大。

2/ BIGINT 很好,即使一个整数可能就足够了。但是也让它成为 UNSIGNED 并且可能是 AUTO_INCREMENT。

3/尽量保持你的用户表尽可能小:

users (
BIGINT id,
VARCHAR(?) username,
VARCHAR(?) password,
VARCHAR(254) email,
DATETIME data_created
)

其余的,您添加了额外的表格:

logins (
BIGINT loginid
BIGINT userid
DATETIME last_login,
VARCHAR(15) IP_ADRESS
...
)

这样,您的 users 表只会在添加或删除新用户或有人更改密码时更改,这比有人登录时少。这允许更好的表缓存(当您写入表时,MySQL 会清除表缓存)。

于 2011-04-11T12:50:54.903 回答
0

这一切都取决于您自己的规格。如果您愿意,用户名可以取 100,密码取您要使用的散列函数的长度(MD5 为 32)。

在表的主键上使用带有 AUTO_INCREMENT 的 INTEGER(10) 更为常见。

您可能想要询问姓名、姓氏、出生日期、居住地等。认为您向用户询问的所有数据对于您正在构建的平台都应该是重要的。

于 2011-04-11T12:51:08.557 回答