在 2 个不相关的表上使用 mysql 触发器
我需要创建一个用户活动日志,然后将其插入数据库中。为此,我正在考虑使用 mysql 触发器,而不是放置一个查询来对每个成功的查询执行此操作。 这2张表根本没有关系。 下面是一个示例:
table_fruits
- 水果名称
- 风味
table_log
- 用户 ID
- 名称
- 表时间戳
table_users
- 用户 ID
现在,每次我在表水果上插入时,将值插入 table_log 的触发器也会执行。我的问题是获取存储在另一个表中的用户 ID。如何确定要插入的用户 ID。据我所知,触发器不需要参数,所以我可能无法使用它来从我的脚本提供 id。 有什么想法吗?我应该为此使用存储过程吗?
I need to create a user activity log which I then insert into the database. And for this, I'm thinking of using mysql triggers instead of placing a query that would do this on every successful query.
The 2 tables have no relationship at all.
Here's an example:
table_fruits
- fruit name
- flavor
table_log
- user id
- name of table
- time stamp
table_users
- user id
Now every time I insert on table fruits, the trigger that would insert the values into table_log would also executes. My problem here is getting the user id which is stored in another table. How do I determine which user id to insert. As far as I know triggers doesn't require parameters, so I can't probably use that to supply the id from my script.
Any ideas? Should I just use stored procedures for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有 3 种方法:
正如您提到的,使用存储过程插入主表和日志表
将用户 ID(由应用提供)存储为主(水果)表中的“inserted_by”列;然后让触发器填充日志表并从主表中读取用户。
让触发器自动找出用户 ID。这有两种风格:
用户 ID 存在于应用程序端,但不存在于数据库端(例如,用户登录到网页,但 CGI 后端代码始终作为特殊的“http”数据库用户连接到数据库)。
应用程序中的用户 ID 实际上作为同名数据库用户连接到数据库。
在这种情况下,您应该使用
USER()
(但NOTcurrent_user()
而是返回创建触发器的人,或者更准确地说,哪个ID用于触发权限检查)There are 3 approaches to this:
As you mentioned, use a stored proc to insert into both main table and a log table
Store the user ID (supplied by the app) as a column in main (fruit) table as "inserted_by" column; then have the trigger populate the log table and read the user from the main table.
Have the trigger automatically figure out the userid. This has two flavors:
User IDs exist on applications side, but NOT on database side (e.g. a user logs in to a web page, but the CGI backend code always connects to a database as special "http" database user).
User ID from the app actually connects to DB as identically named database user.
In this case, you should use
USER()
(but NOTcurrent_user()
which instead returns whoever created the trigger, or more precisely, which ID was used for trigger permission check)当您插入水果表时,您还知道 user_id 值。
我建议像这样创建一个黑洞表:
在黑洞表上放置一个触发器。
现在你的 php 代码变成:
When you insert into the fruits table, you also know the user_id value.
I would suggest create an blackhole table like so:
Put a trigger on the blackhole table.
Now your php code becomes: