自动将用户和日期添加到记录中
我有一个可供多个用户访问的数据库。有什么方法可以设置表格,以便每当有人输入新记录或修改记录时,他/她的用户名和输入的日期都存储在与记录本身相同的表中的两列中。该表看起来像这样:
Id | Name | Username | Date Entered | Date Modified
1 | Cat | john | 1999-05-05 | 1996-06-06
我使用的是 phpMyAdmin 的 GUI。
谢谢!
I have a database which can be accessed by multiple users. Is there any way I can set the tables such that whenever somebody enters a new record or modifies a record, his/her username and the date entered is stored into 2 columns in the same table as the record itself. The table would look like this:
Id | Name | Username | Date Entered | Date Modified
1 | Cat | john | 1999-05-05 | 1996-06-06
I am using a GUI which is phpMyAdmin.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在数据类型声明后使用
NOT NULL
创建表时将列设置为不允许空值。否则,您可以使用 ALTER TABLE 语句来更改已存在的列,或者将该列添加到现有表中。这将阻止某人添加记录,但不会更新。如果您有一个单独的用户表可供引用,您将使用外键关系来确保填充用户列时,将使用有效用户来完成。
如果未提供值,则可以使用 DEFAULT 约束来设置日期字段的值。
You can set a column to not allow null values, either when you create the table using
NOT NULL
after the data type declaration. Otherwise, you use an ALTER TABLE statements to change a column if they already exist, or you are adding the column to an existing table.That will stop someone from adding a record, but not update. If you have a separate table of users to reference, you would use a foreign key relationship to make sure that if the user column is populated, it will be done with a valid user.
DEFAULT constraints can be used to set the value of the date fields if a value is not provided.
首先,您可能需要花一些时间考虑设计审核机制的最佳方法,因为向数据库中的每个表添加两列可能不是最佳选择。
话虽如此,您正在寻找执行您所描述的操作的是触发器。这是每次调用指定操作时都会执行的一段 SQL。您的案例的一个粗略示例:
创建触发器审核
插入“table_name”后
insert (user, time) into "table_name"
我不记得精确的 mysql 语法,但这是您需要的一个粗略示例。如果不清楚,请提出后续问题。
First of all, you may want to spend some time thinking about the best way to design an audit mechanism, because adding two columns to every table in your DB is probably not optimal.
Having said that, what you are looking for to do what you described is a trigger. This is a piece of SQL that will execute every time a specified operation is invoked. A rough example for your case:
create trigger audit
after insert on "table_name"
insert (user, time) into "table_name"
I don't remember the precise mysql syntax, but that's a rough example of what you need. Please ask a follow-up question if that isn't clear.